享元模式(Flyweight),运用共享技术有效地支持大量细粒度的对象。
缺点:使得系统更加复杂;使得程序逻辑复杂化。
Demo:
abstract class Website { public abstract void Use(User user); }
class ConcreteWebsite : Website { private string name; public ConcreteWebsite(string name) { this.name = name; } public override void Use(User user) { Console.WriteLine("网站分类:{0},用户:{1}", name,user.Name); } }
class User { private string name; public User(string name) { this.name = name; } public string Name { get { return name; } } }
class WebsiteFactory { private Hashtable flyweights = new Hashtable(); public Website GetWebsite(string key) { if (!flyweights.ContainsKey(key)) { flyweights.Add(key, new ConcreteWebsite(key)); } return (Website)flyweights[key]; } public int GetWebsiteCount() { return flyweights.Count; } }
Test:
WebsiteFactory wf = new WebsiteFactory(); Website web = wf.GetWebsite("企业网站"); web.Use(new User("Jack")); Website web2 = wf.GetWebsite("企业网站"); web2.Use(new User("Meili")); Console.WriteLine("网站分类总数:{0}", wf.GetWebsiteCount());
时间: 2024-10-25 06:27:17