设计模式-享元模式(Flyweight)


使用共享对象可有效地支持大量的细粒度的对象。要求细粒度的对象,不可避免地使得对象数量多且行之相近,那我们就将这些
对象的信息分为两个部分:内部状态和外部状态。
内部状态:是对象可共享出来的信息,存储在享元对象内部并且不会随环境改变而改变。
外部状态:是对象得以依赖的一个标记,是随环境改变而改变的,不可以共享的状态


设计模式-享元模式(Flyweight)

public abstract class Flyweight {
	// inner state
	private String intrinsic;
	// outside state
	protected final String extrinsic;
	
	public Flyweight(String extrinsic) {
		this.extrinsic = extrinsic;
	}
	
	public abstract void operate();
	
	public String getIntrinsic() {
		return this.intrinsic;
	}
	
	public void setIntrinsic(String intrinsic) {
		this.intrinsic  = intrinsic;
	}
}

public class ConcreteFlyweight1 extends Flyweight {

	public ConcreteFlyweight1(String extrinsic) {
		super(extrinsic);
	}

	// do something depend on outside state
	@Override
	public void operate() {

	}

}

public class ConcreteFlyweight2 extends Flyweight {

	public ConcreteFlyweight2(String extrinsic) {
		super(extrinsic);
	}

	@Override
	public void operate() {
		// TODO Auto-generated method stub

	}

}


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)) {
			flyweight = pool.get(extrinsic);
		} else {
			flyweight = new ConcreteFlyweight1(extrinsic);
			pool.put(extrinsic, flyweight);
		}
		
		return flyweight;
	}
}

你可能感兴趣的:(设计模式)