享元模式

穿精又带淫゛_ 提交于 2020-02-03 01:00:05

一、定义

享元模式(Flyweight),运用共享技术有效的支持大量细粒度的对象。

二、示例代码

/*外部对象*/
public class User {
    private String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public abstract class WebSite {
    public abstract void use(User user);
}

public class ConcreteWebsite extends WebSite{
 private String name;

    public ConcreteWebsite(String name) {
        this.name = name;
    }


    @Override
    public void use(User user) {
        System.out.println("网站名:"+name+",用户名:"+user.getName());
    }
}

import java.util.HashMap;

public class WebsiteFactory {
    private HashMap<String, WebSite> hashMap = new HashMap();

    public WebSite getWebSite(String name) {
        if (hashMap.containsKey(name)) {
            return hashMap.get(name);
        } else {
            ConcreteWebsite concreteWebsite = new ConcreteWebsite(name);
            hashMap.put(name, concreteWebsite);
            return new ConcreteWebsite(name);
        }
    }
    public int countWeb(){
        return hashMap.size();
    }
}

public class Client {
    public static void main(String[] args) {
        WebsiteFactory websiteFactory=new WebsiteFactory();
       WebSite webSite  =websiteFactory.getWebSite("首页");
       User user=new User("huni");
       webSite.use(user);
       WebSite webSite2  =websiteFactory.getWebSite("标题");
       User user2=new User("knock");
       webSite2.use(user2);
       WebSite webSite3  =websiteFactory.getWebSite("标题");
       User user3=new User("jack");
       webSite3.use(user3);
        System.out.println("生成的网站对象数量:"+   websiteFactory.countWeb());


    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!