0
点赞
收藏
分享

微信扫一扫

设计模式-享元模式

有点d伤 2022-04-02 阅读 85
java

一、享元模式介绍

二、享元模式使用

2.1 示例关系:

2.2 代码实现:

/* *
 * 1. 外部状态:用户类。
 */

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;
    }
}



/* *
 * 2. 抽象享元角色:网站类。
 */

abstract class WebSite {

    public abstract void use(User user);
}



/* *
 * 3. 具体享元角色:具体网站类。
 */

class ConcreteWebSite extends WebSite {

    /* *
     * 内部状态:网站发布形式。
     */

    private String type;

    public ConcreteWebSite(String type) {
        this.type = type;
    }

    @Override
    public void use(User user) {
        System.out.println("网站发布形式是 :" + this.type +
                ",用户" + user.getName() + "正在使用网站...");
    }
}



/* *
 * 4. 享元工厂:控制内部状态。
 */

class WebSiteFactory {

    private Map<String, ConcreteWebSite> pool = new HashMap<>(8);

    /* *
     * 获取网站类型。
     */

    public WebSite getWebSiteCategory(String type) {
        // 如果没有该网站发布类型,就在池中创建一个。
        if (!pool.containsKey(type)) {
            pool.put(type, new ConcreteWebSite(type));
        }
        return pool.get(type);
    }

    /* *
     * 获取网站发布种类(当前池的大小)。
     */

    public int getWebSiteCount() {
        return this.pool.size();
    }
}



/* *
 * 客户端调用。
 */

public class Client {

    public static void main(String[] args) {
        WebSiteFactory factory = new WebSiteFactory();
        factory.getWebSiteCategory("微博").use(new User("tom"));
        factory.getWebSiteCategory("微博").use(new User("jack"));
        factory.getWebSiteCategory("知乎").use(new User("lucas"));
        factory.getWebSiteCategory("微信公众号").use(new User("jan"));

        System.out.println("当前网站分类共有" + factory.getWebSiteCount() + "种。");
        // 网站发布形式是 :微博,用户tom正在使用网站...
        // 网站发布形式是 :微博,用户jack正在使用网站...
        // 网站发布形式是 :知乎,用户lucas正在使用网站...
        // 网站发布形式是 :微信公众号,用户jan正在使用网站...
        // 当前网站分类共有3种。
    }

}

三、享元模式总结


举报

相关推荐

0 条评论