设计模式学习11 Flyweight
2010-07-22 10:50
162 查看
应用场景:
解决在系统中存在大量细小对象耗费内存的情况。实现代码:
// 参考:http://java.chinaitlab.com/model/795882_2.html public abstract class Flyweight { public abstract void Operation(); } public class ConcreteFlyWeight : Flyweight { private string str; public ConcreteFlyWeight(string str) { this.str = str; } public override void Operation() { Console.WriteLine("Concrete--flyweight :" + this.str); } } public class FlyweightFactory { private Hashtable flyweights = new Hashtable(); public FlyweightFactory() { } // 这里其实是基于c#本身的语言特性来实现的:c#中将类赋值的话使用的是 // 引用,这里直接返回这个引用。 public Flyweight GetFlyWeight(object obj) { Flyweight flyweight = (Flyweight)this.flyweights[obj]; if (flyweight == null) { flyweight = new ConcreteFlyWeight((string)obj); this.flyweights.Add(obj, flyweight); } return flyweight; } public int GetFactorySize() { return this.flyweights.Count; } } public class FlyWeightPattern { FlyweightFactory factory = new FlyweightFactory(); Flyweight fly1; Flyweight fly2; Flyweight fly3; Flyweight fly4; Flyweight fly5; Flyweight fly6; public FlyWeightPattern() { // ... fly1 = factory.GetFlyWeight("Google"); fly2 = factory.GetFlyWeight("qutr"); fly3 = factory.GetFlyWeight("Google"); fly4 = factory.GetFlyWeight("Google"); fly5 = factory.GetFlyWeight("Google"); fly6 = factory.GetFlyWeight("Google"); } public void ShowFlyweight() { // ... fly1.Operation(); fly2.Operation(); fly3.Operation(); fly4.Operation(); fly5.Operation(); fly6.Operation(); int size = factory.GetFactorySize(); Console.WriteLine("size = " + size); } public static void Main(string[] args) { Console.WriteLine("The FlyWeight Pattern!"); FlyWeightPattern pattern = new FlyWeightPattern(); pattern.ShowFlyweight(); } }
相关文章推荐
- 设计模式学习11 Flyweight
- C++学习 11 设计模式 1
- 设计模式学习笔记(11)——装饰者模式
- 设计模式学习--------11.中介者模式学习
- FlyWeight模式——设计模式学习笔记
- 11. JAVA常用类库 Part 4 (对象克隆技术clone、Arrays类、Comparable接口、比较器Comparator、观察者设计模式) ----- 学习笔记
- 【设计模式】学习笔记11:模板方法(Template Method)
- 步步为营 .NET 设计模式学习笔记 十七、Flyweight(享元模式)
- IOS设计模式学习(11)中介者
- JAVA设计模式学习第一天 设计模式之Flyweight——打球篇
- FlyWeight模式——设计模式学习笔记
- 设计模式深入学习--Flyweight 享元模式(结构型模式)
- 设计模式(11)-结构型-享元模式(Flyweight)
- 设计模式学习笔记(二十二)—FlyWeight享元模式
- 设计模式学习笔记(十二)——Flyweight享元模式
- 设计模式学习笔记--Flyweight享元模式
- HeadFirst 设计模式学习笔记11——状态模式
- 学习php设计模式 php实现享元模式(flyweight)
- 学习php设计模式 php实现享元模式(flyweight)
- 【设计模式】学习笔记11:模板方法(Template Method)