享元模式

定义

运用共享技术减少对象数量

适用场景

  1. 池技术
  2. 系统有大量相同对象

应用案例

  1. JDK中的String,常量池中存在时直接返回,没有则创建放入池中
  2. 数据库连接池

代码

public interface Boll {
    void logColor();
}
public class ColorBoll implements Boll {

    private static final Map<String,Boll> STRING_BOLL_MAP = new HashMap<>();

    private String color;

    public ColorBoll(String color) {
        this.color = color;
    }

    @Override
    public void logColor() {
        System.out.println(this.color);
    }

    public static Boll getBoll(String color){
        Boll boll = STRING_BOLL_MAP.get(color);

        if (boll == null){
            boll = new ColorBoll(color);
            STRING_BOLL_MAP.put(color,boll);
            System.out.println("创建了boll : "+color);
        }
        return boll;
    }
}
public class Test {
    public static void main(String[] args) {
        Boll boll = ColorBoll.getBoll("red");
        boll.logColor();

        boll = ColorBoll.getBoll("blue");
        boll.logColor();

        boll = ColorBoll.getBoll("blue");
        boll.logColor();

        boll = ColorBoll.getBoll("blue");
        boll.logColor();

        boll = ColorBoll.getBoll("red");
        boll.logColor();

        boll = ColorBoll.getBoll("yellow");
        boll.logColor();

    }
}
创建了boll : red
red
创建了boll : blue
blue
blue
blue
red
创建了boll : yellow
yellow
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值