设计模式 享元模式

概述

结构

案例

代码

编写一个抽象类 定义共同属性和行为

public abstract class AbstractBox {
    public abstract String getSharp();
    public void display(String color){
        System.out.println("形状 "+this.getSharp()+"颜色 "+color);
    }
}

定义几个形状类

public class IBox extends AbstractBox{
    @Override
    public String getSharp() {
        return "I";
    }
}
public class LBox extends AbstractBox{
    @Override
    public String getSharp() {
        return "L";
    }
}

通过单例模式定义一个工厂类

public class BoxFactory {
    private static HashMap<String,AbstractBox> map;

    private BoxFactory(){
        map = new HashMap<>();
        AbstractBox iBox = new IBox();
        AbstractBox lBox = new LBox();
        map.put("I",iBox);
        map.put("L",lBox);
    }

    public static final BoxFactory getInstance() {
        return SingleHolder.INSTANCE;
    }

    private static class SingleHolder{
        private static final BoxFactory INSTANCE = new BoxFactory();
    }

    public AbstractBox getBox(String key){
        return map.get(key);
    }
}

测试使用:

public class Test {
    public static void main(String[] args) {
        BoxFactory factory = BoxFactory.getInstance();
        AbstractBox lBox = factory.getBox("L");
        lBox.display("红色");
        AbstractBox lBox2 = factory.getBox("L");
        lBox2.display("蓝色");
        System.out.println("是否是同一个对象"+(lBox == lBox2));
    }
}

总结

posted @ 2021-10-12 17:37  一个经常掉线的人  阅读(34)  评论(0)    收藏  举报