享元模式:避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类).
WebSite:
package ding.study.designpatterns.flyweight; /** * 网站抽象类 * @author daniel * @email [email protected] * @time 2016-5-30 上午10:50:31 */ public abstract class WebSite { public abstract void use(); }
WebSiteFactory
package ding.study.designpatterns.flyweight; /** * 网站实现类 * @author daniel * @email [email protected] * @time 2016-5-30 上午10:51:35 */ public class WebSiteImpl extends WebSite{ //网站分类名称 private String name=""; /** * 构造函数 * @param name */ public WebSiteImpl(String name){ this.name=name; } /** * 显示名称 */ @Override public void use() { System.out.println("网站分类:"+this.name); }}
package ding.study.designpatterns.flyweight; import java.util.Hashtable; /** * 网站工厂 * * @author daniel * @email [email protected] * @time 2016-5-30 上午10:52:25 */ public class WebSiteFactory { private Hashtable<String, WebSite> flyweights = new Hashtable<String, WebSite>(); /** * 获得网站分类 * 这里可以有多个网站实现类 * @param key * @return */ public WebSite getWebSiteCategory(String key) { if (!flyweights.containsKey(key)) { flyweights.put(key, new WebSiteImpl(key)); } return (WebSite) flyweights.get(key); } /** * 获得网站分类总数 * * @return */ public int getWebSiteCount() { return flyweights.size(); } }
ZTestMain
package ding.study.designpatterns.flyweight; /** * 享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。 * * 避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类). 输出结果 * @author daniel * @email [email protected] * @time 2016-5-30 上午10:53:34 */ public class ZTestMain { /** * @author daniel * @time 2016-5-30 上午10:53:24 * @param args */ public static void main(String[] args) { WebSiteFactory f=new WebSiteFactory(); WebSite fx=f.getWebSiteCategory("科技类"); fx.use(); WebSite fx1=f.getWebSiteCategory("新闻类"); fx1.use(); WebSite fx2=f.getWebSiteCategory("娱乐类"); fx2.use(); WebSite fy=f.getWebSiteCategory("博客"); fy.use(); WebSite fz=f.getWebSiteCategory("博客"); fz.use(); System.out.println("网站分类总数为:"+f.getWebSiteCount()); } }
https://github.com/dingsai88/StudyTest/tree/master/src/ding/study/designpatterns/flyweight