【设计模式】——享元模式(23)

帅比萌擦擦* 提交于 2019-12-22 18:42:43

一、定义

享元模式就是运用共享技术有效的支持大量细粒度的对象。

二、框架运用

String中的享元模式

三、实战

1、实现类

public abstract class WebSite {
    protected String name;

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

    public abstract void show(User user);
}


public class ConcreteWebSite extends WebSite {
    public ConcreteWebSite(String name) {
        super(name);
    }

    @Override
    public void show(User user) {
        System.out.println("网站名称:"+name+"|网站账号:"+user.getAccount()+"|网站密码:"+user.getPassword());
    }

2、实体类

@Data
public class User {
    private String account;
    private String password;

    public User(String account, String password) {
        this.account = account;
        this.password = password;
    }
}

3、工厂类

public class WebSiteFactory {
    private Map<String,WebSite> webSiteMap = new HashMap<>();

    public WebSite getWebSite(String key){
        if (!webSiteMap.containsKey(key)){
            webSiteMap.put(key,new ConcreteWebSite(key));
        }
        return webSiteMap.get(key);
    }

    public int getWebSiteCount(){
        return webSiteMap.size();
    }
}

4、运行和结果

public class Client {
    public static void main(String[] args) {
        WebSiteFactory factory = new WebSiteFactory();

        WebSite webSiteA = factory.getWebSite("A");
        WebSite webSiteB = factory.getWebSite("B");

        User userA = new User("范闲","123456");
        User userB = new User("王启年","654321");
        webSiteA.show(userA);
        webSiteB.show(userB);
        System.out.println(factory.getWebSiteCount());
    }
}



Connected to the target VM, address: '127.0.0.1:56232', transport: 'socket'
网站名称:A|网站账号:范闲|网站密码:123456
网站名称:B|网站账号:王启年|网站密码:654321
2
Disconnected from the target VM, address: '127.0.0.1:56232', transport: 'socket'

 

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