享元模式

    xiaoxiao2023-10-29  137

    定义

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

    适用场景

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

    应用案例

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

    代码

    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
    最新回复(0)