《大话设计模式》Java代码示例(二十二)之享元模式

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

《大话设计模式》Java代码示例(二十二)之享元模式_第1张图片

package flyweight;

/**
 * 享元模式(Flyweight)
 * 用户类
 */
public class User {

    private String name;

    public String getName() {
        return name;
    }

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

}
package flyweight;

/**
 * 享元模式(Flyweight)
 * 网站抽象类
 */
public abstract class WebSite {

    public abstract void use(User user);

}
package flyweight;

/**
 * 享元模式(Flyweight)
 * 具体网站类
 */
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());
    }

}
package flyweight;

import java.util.Hashtable;

/**
 * 享元模式(Flyweight)
 * 网站工厂类
 */
public class WebSiteFactory {

    private Hashtable flyweights = new Hashtable();

    // 获得网站分类
    public WebSite getWebSiteCategory(String key) {
        if (!flyweights.contains(key)) {
            flyweights.put(key, new ConcreteWebSite(key));
        }
        return (WebSite) flyweights.get(key);
    }

    // 获得网站分类总数
    public int getWebSiteCount() {
        return flyweights.size();
    }

}
package flyweight;

/**
 * 享元模式(Flyweight)
 * 客户端main方法
 */
public class Client {

    public static void main(String[] args) {
        WebSiteFactory f = new WebSiteFactory();
        WebSite fx = f.getWebSiteCategory("产品展示");
        fx.use(new User("小菜"));

        WebSite fy = f.getWebSiteCategory("产品展示");
        fy.use(new User("大鸟"));

        WebSite fz = f.getWebSiteCategory("产品展示");
        fz.use(new User("娇娇"));

        WebSite fl = f.getWebSiteCategory("博客");
        fl.use(new User("老顽童"));

        WebSite fm = f.getWebSiteCategory("博客");
        fm.use(new User("桃谷六仙"));

        WebSite fn = f.getWebSiteCategory("博客");
        fn.use(new User("南海鳄神"));

        System.out.println("得到网站分类总数为" + f.getWebSiteCount());

    }

}

 

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