第十二篇 设计模式--享元模式

定义:运用共享技术有效地支持大量细粒度对象。

代码:

package flyweight_model;

import java.util.Hashtable;

/**
 * @author naivor
 *		享元模式-场景类
 */
public class FlyweightModel {
	public static void main(String[] args) {
		FlyweightFactory factory=new FlyweightFactory();
		Flyweight flyweight=factory.getFlayweight("A");
		flyweight.operate();
		
		UnSharedFlyweight unFlyweight=new UnSharedFlyweight();
		unFlyweight.operate();
	}
}
/**
 * 
 * @author naivor
 *		享元模式-享元抽象类
 */
abstract class Flyweight{
	public abstract void operate();
}
/**
 * 
 * @author naivor
 *		享元模式-共享的Flyweight子类
 */
class SharedFlyweight extends Flyweight{
	@Override
	public void operate() {
		//SharedFlyweight的业务逻辑
	}
	
}
/**
 * 
 * @author naivor
 *		享元模式-非共享的Flyweight子类
 */
class UnSharedFlyweight extends Flyweight{
	@Override
	public void operate() {
		//UnSharedFlyweight的业务逻辑
	}
	
}
/**
 * 
 * @author naivor
 *		享元模式-享元工厂类
 */
class FlyweightFactory {
	private Hashtable<String, Flyweight> flyweights=new Hashtable<String, Flyweight>();
	public FlyweightFactory() {
		flyweights.put("A", new SharedFlyweight());
		flyweights.put("B", new SharedFlyweight());
		flyweights.put("C", new SharedFlyweight());
	}
	
	public Flyweight getFlayweight(String type){
		Flyweight flyweight=flyweights.get(type);
		
		if (flyweight==null) {
			flyweight=new SharedFlyweight();
			flyweights.put(type, flyweight);
		}
		
		return flyweight;
	}
}


你可能感兴趣的:(设计模式,软件设计,扩展,结构)