享元模式

一、定义

享元模式(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());


    }
}

posted @ 2020-02-03 00:22  兮云飞扬  阅读(91)  评论(0编辑  收藏  举报