大话设计模式-享元模式

需求
有一群类似的商家客户,需要提供一个网站,网站实现的功能有信息发布、产品展示、博客留言、论坛等。
实现
级别1

public class WebSite
{
	private String name="";
	public WebSite(String name)
	{
		this.name=name;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name=name;
	}
	public void use()
	{
		System.out.println("网站分类:"+getName());
	}
}
public class Main
{
	public static void main(String[] args)
    {  
       WebSite A=new WebSite("产品展示");
       A.use();
       WebSite B=new WebSite("产品展示");
       B.use();
       WebSite C=new WebSite("博客");
       C.use();
       WebSite D=new WebSite("博客");
       D.use();
    }  
}
如果要做两个产品展示,两个博客的网站,就需要四个网站类的实例。但是它们本质上都是一样的代码,如果网站增多,实例也就随着增多,这对服务器的资源浪费很严重。
级别2
public class User 
{
    private String name;
    public User(String name)
    {
        this.name=name;
    }
    public String getName() 
    {
        return name;
    }
    public void setName(String name) 
    {
        this.name=name;
    }
}
public abstract class WebSite 
{
    public abstract void setUser(User user);
}
public class ConcreteWebSite extends WebSite
{
    private String name="";
    public ConcreteWebSite(String name) 
    {
        this.name=name;
    }
    @Override
    public void setUser(User user) 
    {
        System.out.println("网站分类:"+name+" 用户:"+user.getName());       
    }
}
public class WebSiteFactory 
{
    private Hashtable flyweights=new Hashtable();
    public WebSite getWebSiteCategory(String key)
    {
        if((WebSite)flyweights.get(key)==null) 
        {
            flyweights.put(key,new ConcreteWebSite(key));
        }
        return (WebSite)flyweights.get(key);
    }
    public int getWebSiteCount()
    {
        return flyweights.size();
    }
}
public class Main
{  	  
    public static void main(String[] args)
    {  
        WebSiteFactory webSiteFactory=new WebSiteFactory();
        WebSite webSiteA=webSiteFactory.getWebSiteCategory("产品展示");
        webSiteA.setUser(new User("Tom"));
        WebSite webSiteB=webSiteFactory.getWebSiteCategory("产品展示");
        webSiteB.setUser(new User("Jack"));
        WebSite webSiteC=webSiteFactory.getWebSiteCategory("博客留言");
        webSiteC.setUser(new User("Sarah"));
        WebSite webSiteD=webSiteFactory.getWebSiteCategory("博客留言");
        webSiteD.setUser(new User("Jerry"));
        System.out.println("共需要构建 "+webSiteFactory.getWebSiteCount()+"种类型的网站");
    }  
}  
享元模式,主要用于减少创建对象的数量。享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。主要解决在有大量对象时,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。









你可能感兴趣的:(大话设计模式-享元模式)