设计模式之享元模式

享元模式的本质:就是做了一层缓存,在传参数进来的时候,我们先去查这个缓存里面是否存在,如果存在直接返回对象,如果不存在我们就创建对象然后存在map里面,达到减少内存的占用和创建对象的开销,从而提高了性能

1.汽车类

public class Cart {
    //模具的形状
    private String shape;
    //模具的材料
    private String material;

    public void productCart(String brand){
        System.out.println("生产一辆"+brand+"品牌的汽车:"+shape+"模具材料"+material);
    }

    public void setShape(String shape) {
        this.shape = shape;
    }

    public void setMaterial(String material) {
        this.material = material;
    }
}

2.创建汽车模具享元工厂类

public class XiangYuanFactory {

  private Map<String,Cart> cartMap =new ConcurrentHashMap<>();

  public Cart getCart(String shape,String material){
      String key=shape + "_" +material;
      Cart cart = cartMap.get(key);
      if (cart==null){
          cart = new Cart();
          cart.setShape(shape);
          cart.setMaterial(material);
          cartMap.put(key,cart);
      }
      return cart;
  }
}

3.测试

public class test05 {
    public static void main(String[] args) {
        XiangYuanFactory xiangYuanFactory = new XiangYuanFactory();
        Cart factoryCart = xiangYuanFactory.getCart("轿车", "钢铁");
        factoryCart.productCart("奥迪");
        Cart factoryCart1 = xiangYuanFactory.getCart("轿车", "钢铁");
        factoryCart1.productCart("宝马");

        Cart factoryCart2 = xiangYuanFactory.getCart("SUV", "碳纤维");
        factoryCart2.productCart("特斯拉");

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值