享元模式
using System;
using System.Web;
using System.Collections;
//面向对象的思想很好地解决了抽象性的问题,一般也不会出现性能上的问题。但是在某些情况下,对象的数量可能会太多,从而导致了运行时的代价。
//那么我们如何去避免大量细粒度的对象,同时又不影响客户程序使用面向对象的方式进行操作?
//运用共享技术有效地支持大量细粒度的对象。[GOF 《设计模式》]
//场景:各位同学,把你们的亲戚朋友的详细信息都统计过来哦 假设每个人的名字是唯一的,实在不服。就拿身份证号来说事
public partial class DesignPattern_Flyweight : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PeopleFactory peopleFactory = PeopleFactory.CreatFactory();
Peoples a = peopleFactory.GetPeople("李大华", "李明他爹", "193");
a.Print();
Peoples b = peopleFactory.GetPeople("李大华", "李小明他二叔子", "193");
b.Print();
Peoples c = peopleFactory.GetPeople("李大华", "李二明他舅舅", "193");
c.Print();
Peoples d = peopleFactory.GetPeople("陈水扁", "小泉他丈人", "156");
d.Print();
Peoples g = peopleFactory.GetPeople("陈水扁", "BUS他小蜜", "156");
g.Print();
Peoples f = peopleFactory.GetPeople("棒子", "美国的狗", "322");
f.Print();
Response.Write("档案总人数" + peopleFactory.GetCount()+"<br>");
NewPeople p = new NewPeople(a);
p.Color = "yellow";
NewPeople p2 = new NewPeople(a);
p2.Color = "Red";
p2.Prints();
p.Prints();
}
}
public class Peoples
{
public string Name;
public string Wight;
public string Identity;
public Peoples(string name)
{
this.Name = name;
}
public void Print()
{
HttpContext.Current.Response.Write("家属姓名:" + Name + " 体重:" + Wight + " 身份:" + Identity + "<br>");
}
}
public class PeopleFactory
{
public static PeopleFactory peopleFactory;
public static PeopleFactory CreatFactory()
{
if (peopleFactory == null)
{
peopleFactory = new PeopleFactory();
}
return peopleFactory;
}
public int GetCount()
{
return htPeoples.Count;
}
Hashtable htPeoples = new Hashtable();
public Peoples GetPeople(string name, string Identity, string weight)
{
Peoples people = (Peoples)htPeoples[name];
if (people == null)
{
people = new Peoples(name);
people.Wight = weight;
htPeoples.Add(name, people);
}
people.Identity = Identity;
return people;
}
}
//关于享元的一点思考,扩展
public class NewPeople
{
Peoples P;
public NewPeople(Peoples p)
{
this.P = p;
}
public string Color;
public void Prints()
{
HttpContext.Current.Response.Write(this.Color);
P.Print();
}
}