设计模式之享元(flyweight)

public class Flyweight {

	class FlyweightFactory {
		Hashtable<String, FlyWeight> pool = new Hashtable<String, FlyWeight>();

		public void addFlyWeight(String key, FlyWeight value) {
			pool.put(key, value);
		}
		//其实就是一个池的维护,在创建新对象时,又涉及到工厂模式创建新对象
		public FlyWeight getFlyWeight(String key) {
			FlyWeight fw = pool.get(key);
			if (null == fw) {
				fw = new ConcreteFlyWeight("pool instance key is " + key);
				pool.put(key, fw);
			}
			return fw;
		}
	}

	interface FlyWeight {
		public void print();
	}
	//共享类
	class ConcreteFlyWeight implements FlyWeight {
		String param;

		public ConcreteFlyWeight(String param) {
			this.param = param;
		}

		public void print() {
			System.out.println("flyweight..." + param);
		}
	}
	//不被共享的类
	class UnConcreteFlyWeight implements FlyWeight {
		public void print() {
		}
		
	}
	public static void main(String[] args) {
		Flyweight fw = new Flyweight();
		FlyweightFactory fwf = fw.new FlyweightFactory();
		fwf.addFlyWeight("key1", fw.new ConcreteFlyWeight("key1 flyweight..."));
		fwf.addFlyWeight("key2", fw.new ConcreteFlyWeight("key2 flyweight..."));
		fwf.getFlyWeight("key1").print();
		fwf.getFlyWeight("key2").print();
		fwf.getFlyWeight("key3").print();
	}
}
//http://zuoqiang.iteye.com/blog/743962
 

你可能感兴趣的:(flyweight,享元模式)