享元模式(Flyweight)
享元模式,运用共享技术有效地支持大量细粒度的对象。
代码
1.代码如下:
网站抽象类
using System;
namespace WebSite
{
//网站抽象类
public abstract class WebSite
{
public abstract void Use(User user);
}
}
具体网站类
using System;
namespace WebSite
{
//具体网站类
public class ConcreteWebSite:WebSite
{
private string name="";
public ConcreteWebSite (string name)
{
this.name = name;
}
public override void Use (User user)
{
Console.WriteLine ("网站分类:" + name + "用户:" + user.Name);
}
}
}
网站工厂类
using System;
using System.Collections;
namespace WebSite
{
//网站工厂类
public class WebSiteFactory
{
private Hashtable flyweights=new Hashtable();
//获得网站分类
public WebSite GetWebSiteCategory(string key){
if (!flyweights.ContainsKey (key)) {
flyweights.Add (key, new ConcreteWebSite (key));
}
return((WebSite)flyweights [key]);
}
//获得网站分类总数
public int GetWebSiteCount(){
return flyweights.Count;
}
}
}
用户类
using System;
namespace WebSite
{
//用户类
public class User
{
//名字
private string name;
public User (string name)
{
this.name = name;
}
public string Name {
get {
return name;
}
}
}
}
2.客户端代码如下:
客户端
using System;
namespace WebSite
{
class MainClass
{
public static void Main (string[] args)
{
WebSiteFactory webSiteFactory = new WebSiteFactory ();
WebSite webSite1 = webSiteFactory.GetWebSiteCategory ("产品展示");
webSite1.Use (new User("张三"));
WebSite webSite2 = webSiteFactory.GetWebSiteCategory ("产品展示");
webSite2.Use (new User("李四"));
WebSite webSite3 = webSiteFactory.GetWebSiteCategory ("产品展示");
webSite3.Use (new User("王五"));
WebSite webSite4 = webSiteFactory.GetWebSiteCategory ("博客");
webSite4.Use (new User("李六"));
WebSite webSite5 = webSiteFactory.GetWebSiteCategory ("博客");
webSite5.Use (new User("钱七"));
WebSite webSite6 = webSiteFactory.GetWebSiteCategory ("博客");
webSite6.Use (new User("田八"));
Console.WriteLine ("网站分类总数为{0}", webSiteFactory.GetWebSiteCount ());
}
}
}
3.运行结果