码迷,mamicode.com
首页 > 其他好文 > 详细

享元模式

时间:2016-08-09 09:30:38      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

定义:使用享元对象可有效的支持大量的细粒度的对象


类图:

技术分享


代码:

public abstract class Flyweight {

	private String intrinsic;
	
	protected final String extrinsic;
	
	public Flyweight(String extrinsic){
		this.extrinsic = extrinsic;
	}
	
	public abstract void operator();
	
	public String getInstrinsic(){
		return intrinsic;
	}
	
	public void setInstrinsic(String instrinsic){
		this.intrinsic = instrinsic;
	}
}

public class ConcreteFlyweight1 extends Flyweight{


	public ConcreteFlyweight(String extrinsic) {
		super(extrinsic);
		// TODO Auto-generated constructor stub
	}

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

}
public class ConcreteFlyweight2 extends Flyweight{


	public ConcreteFlyweight(String extrinsic) {
		super(extrinsic);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void operator() {
		// 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;
	}
}

优点:

大大减少应用程序创建的对象


缺点:

线程安全



享元模式

标签:

原文地址:http://blog.csdn.net/renpengddxx/article/details/52159509

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!