您当前的位置: 首页 > 

命运之手

暂无认证

  • 3浏览

    0关注

    747博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【设计模式】【25】享元模式

命运之手 发布时间:2022-05-02 17:46:09 ,浏览量:3

应用场景

享元模式,英文名Flyweight Pattern

该模式通过对象复用,来避免大量创建复杂对象

主要用于线程池,连接池等场景,实现上比较简单

代码实现


	public class Product {
	
	}


	//每种类型的产品,共享一个对象
	public class ProductFactory {
	
	    //对象复用池
	    private static final Map pool = new HashMap();
	    //对象使用状态
	    private static final Map usage = new HashMap();
	
	    synchronized public static Product obtain(String type) {
	        //对象不存在,创建新对象
	        if (!pool.containsKey(type)) {
	            Product product = new Product();
	            pool.put(type, product);
	            usage.put(type, true);
	            return product;
	        }
	        //对象正在使用
	        if (usage.get(type))
	            throw new RuntimeException("object is in usage");
	        //复用旧对象
	        usage.put(type, true);
	        return pool.get(type);
	    }
	
	    //释放对象
	    synchronized public static void release(Product product) {
	        for (String type : pool.keySet())
	            if (pool.get(type) == product)
	                usage.put(type, false);
	    }
	}

关注
打赏
1654938663
查看更多评论
立即登录/注册

微信扫码登录

0.0377s