大话设计模式-享元模式的实践-网站模板享元

UML

大话设计模式-享元模式的实践-网站模板享元_第1张图片

用户类 用于网站的客户账号 是网站类的外部状态

/**
 * @ClassName: User
 * @Author: Leo
 * @Description: 用户类 用于网站的客户账号 是网站类的外部状态
 * @Date: 2019/5/28 9:58
 */
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;
    }
}

网站抽象类

/**
 * @ClassName: WebSite
 * @Author: Leo
 * @Description: 网站抽象类
 * @Date: 2019/5/28 10:00
 */
public abstract class WebSite {
    /**
     * 模拟用户使用网站
     *
     * @param user
     */
    public abstract void use(User user);
}

具体的网站

/**
 * @ClassName: ConcreteWebSite
 * @Author: Leo
 * @Description: 具体的网站
 * @Date: 2019/5/28 10:05
 */
public class ConcreteWebSite extends WebSite {
    private String websiteName;

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

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

网站工厂

import java.util.Hashtable;

/**
 * @ClassName: WebSiteFactory
 * @Author: Leo
 * @Description: 网站工厂
 * @Date: 2019/5/28 10:10
 */
public class WebSiteFactory {
    private Hashtable<String, WebSite> hashtable = new Hashtable<>();

    public WebSite getWebSite(String key) {
        if (hashtable.containsKey(key)) {
            return hashtable.get(key);
        } else {
            WebSite concreteWebSite = new ConcreteWebSite(key);
            hashtable.put(key, concreteWebSite);
            return concreteWebSite;
        }
    }

    public int getCount() {
        return hashtable.size();
    }
}

测试类

/**
 * @ClassName: Main
 * @Author: Leo
 * @Description: 测试类
 * @Date: 2019/5/28 9:58
 */
public class Main {
    public static void main(String[] args) {
        WebSiteFactory factory = new WebSiteFactory();

        //以下三个是同一个享元对象
        WebSite f1 = factory.getWebSite("产品展示");
        f1.use(new User("小菜"));

        WebSite f2 = factory.getWebSite("产品展示");
        f2.use(new User("大鸟"));

        WebSite f3 = factory.getWebSite("产品展示");
        f3.use(new User("笨蛋"));


        WebSite f31 = factory.getWebSite("博客");
        f31.use(new User("钢蛋"));

        WebSite f32 = factory.getWebSite("博客");
        f32.use(new User("鸡蛋"));

        WebSite f33 = factory.getWebSite("博客");
        f33.use(new User("大神"));

        System.out.println("网站总数--->" + factory.getCount());
    }
}

运行结果

大话设计模式-享元模式的实践-网站模板享元_第2张图片

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