首页 > 代码库 > 享元模式

享元模式

/**
 * 抽象享元角色
 * @author 
 * @date 2014-10-15
 */
public abstract class FlyWeight {
	/**
	 * 内部状态
	 */
	private String intrinsic;
	
	/**
	 * 外部状态
	 */
	protected final String extrinsic; 
	/**
	 * 构造方法
	 */
	public FlyWeight(String _extrinsic){
		this.extrinsic = _extrinsic;
	}
	
	public abstract void oprater();

	public String getIntrinsic() {
		return intrinsic;
	}

	public void setIntrinsic(String intrinsic) {
		this.intrinsic = intrinsic;
	}
	
	
}
public class FlyWeightFactory {
    /**
     * 定义一个池容器
     */
	private static HashMap<String, FlyWeight> pool = new HashMap<String,FlyWeight>();
	/**
	 * 享元工厂
	 */
	public static FlyWeight getFlyWeight(String extrinsic){
		/**
		 * 定义返回的元素
		 */
		FlyWeight flyWeight = null;
		/**
		 * 判断池容器是否存在该对象
		 */
		if(pool.containsKey(extrinsic)){
			System.out.println(extrinsic+"从池容器中取出");
			flyWeight = pool.get(extrinsic);
		}else{
			System.out.println(extrinsic+"放到池容器中");
			flyWeight = new ConcreateFlyWeight(extrinsic);
			pool.put(extrinsic, flyWeight);
		}
		return flyWeight;
	}
	public class ConcreateFlyWeight extends FlyWeight {

	public ConcreateFlyWeight(String _extrinsic) {
		super(_extrinsic);
	}

	@Override
	public void oprater() {
		System.out.println("享元模式2。。。。。。。。。。。");
	}
	}
	public class ConcreateFlyWeight1 extends FlyWeight {

	public ConcreateFlyWeight1(String _extrinsic) {
		super(_extrinsic);
	}

	@Override
	public void oprater() {
		System.out.println("享元模式1。。。。。。。。");	
	}

}


享元模式