定义:
享元模式:避免大量具有相同内容的小类的开消(如耗费内存),使大家同享1个类(元类).
结构图:
WebSite:
package ding.study.designpatterns.flyweight;
/**
* 网站抽象类
* @author daniel
* @email 576699909@qq.com
* @time 2016⑸⑶0 上午10:50:31
*/
public abstract class WebSite {
public abstract void use();
}
WebSiteFactory
package ding.study.designpatterns.flyweight;
/**
* 网站实现类
* @author daniel
* @email 576699909@qq.com
* @time 2016⑸⑶0 上午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);
}}
WebSiteImpl
package ding.study.designpatterns.flyweight;
import java.util.Hashtable;
/**
* 网站工厂
*
* @author daniel
* @email 576699909@qq.com
* @time 2016⑸⑶0 上午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):应用同享技术有效地支持大量细粒度的对象。
*
* 避免大量具有相同内容的小类的开消(如耗费内存),使大家同享1个类(元类).
输出结果
* @author daniel
* @email 576699909@qq.com
* @time 2016⑸⑶0 上午10:53:34
*/
public class ZTestMain {
/**
* @author daniel
* @time 2016⑸⑶0 上午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