说明
1.建立抽象享元产品AbsFlyweight,使FlyweightA,FlyweightB继承他,并且具体产品的属性不相同,处理好外部参数和内部参数
2.建立享元工厂FlyweightFactory并聚合抽象享元产品,只需要new出所有具体产品并通过外部参数的传递,实现不同的功能,降低创建大型对象的内存消耗
3.建立享元管理器执行AbsFlyweight的方法
public abstract class AbsFlyweight { public abstract void Exc(int a, int b, int c); public abstract void Exc(); } class FlyweightA : AbsFlyweight { int a, b, c; public override void Exc(int a, int b, int c) { } public override void Exc() { } public FlyweightA() { } public FlyweightA(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class FlyweightB : AbsFlyweight { int a, b; public FlyweightB(int a, int b) { this.a = a; this.b = b; } public FlyweightB() { } public override void Exc(int a, int b, int c) { } public override void Exc() { } } public class FlyweightFactory { List<AbsFlyweight> lAbsFlyweight; public FlyweightFactory() { lAbsFlyweight = new List<AbsFlyweight>(); lAbsFlyweight.Add(new FlyweightA()); lAbsFlyweight.Add(new FlyweightB()); } public AbsFlyweight Get(int index) { return lAbsFlyweight[index]; } } public class FlyweightManage { int[] la, lb, lc,ltype; Random r; int count; public FlyweightManage(int count, Random r) { this.r = r; this.count = count; la =new int[count]; lb = new int[count]; lc = new int[count]; ltype = new int[count]; for (int i = 0; i < count; i++) { la[i]=(r.Next()); lb[i]=(r.Next()); lc[i]=(r.Next()); ltype[i] = r.Next() % 2; } } public void Exc() { FlyweightFactory fact = new FlyweightFactory(); for (int i = 0; i < count; i++) { fact.Get(r.Next(ltype[i])).Exc(la[i], lb[i], lc[i]); } } } int count = 10000000; Random r = new Random(); Console.WriteLine("不使用享元创建对象"); Stopwatch watch1 = new Stopwatch(); watch1.Start(); List<AbsFlyweight> lAbsFlyweight = new List<AbsFlyweight>(); for (int i=0;i<count;i++) { AbsFlyweight f; if (r.Next()%2==0) { f = new FlyweightA(r.Next(), r.Next(), r.Next()); } else { f = new FlyweightB(r.Next(), r.Next()); } lAbsFlyweight.Add(f); } foreach(var eAbsFlyweight in lAbsFlyweight) { eAbsFlyweight.Exc(); } watch1.Stop(); Console.WriteLine("用时:"+watch1.ElapsedMilliseconds); Console.WriteLine("使用享元创建对象"); watch1.Reset(); watch1.Start(); FlyweightManage flyweightManage = new FlyweightManage(count,r); flyweightManage.Exc(); watch1.Stop(); Console.WriteLine("用时:" + watch1.ElapsedMilliseconds);