享元模式(Flyweight)Java


定义:

享元模式:避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类).



结构图:


享元模式(Flyweight)Java_第1张图片


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

	 }}





WebSiteImpl

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 flyweights = new Hashtable();

	/**
	 * 获得网站分类
	 * 这里可以有多个网站实现类
	 * @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
















你可能感兴趣的:(享元模式(Flyweight)Java)