享元设计模式

享元设计模式_第1张图片享元设计模式_第2张图片

package com.jmj.pattern.flyweight;

public abstract class AbstractBox {

    //获取图形的方法
    public abstract String getShape();

    //显示图形及颜色
    public void diplay(String color){
        System.out.println("方块形状:"+getShape()+",颜色:"+color);
    }




}
package com.jmj.pattern.flyweight;

import java.util.HashMap;

/**
 * 将该类设计为工厂类 单例模式
 */
public class BoxFactory {

    private HashMap map;

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

    //提供一个方法获取该工厂类对象
    public static BoxFactory getInstance(){
        return boxFactory;
    }
    private static BoxFactory boxFactory=new BoxFactory();

    public AbstractBox getShape(String name){
        return map.get(name);
    }


}
package com.jmj.pattern.flyweight;

public class IBox extends AbstractBox{
    @Override
    public String getShape() {
         return "I";
    }
}
package com.jmj.pattern.flyweight;

public class LBox extends AbstractBox{
    @Override
    public String getShape() {
         return "L";
    }
}
package com.jmj.pattern.flyweight;

public class OBox extends AbstractBox{
    @Override
    public String getShape() {
         return "O";
    }
}
package com.jmj.pattern.flyweight;

public class Client {
    public static void main(String[] args) {
        AbstractBox i = BoxFactory.getInstance().getShape("I");
        i.diplay("灰色");
        AbstractBox l = BoxFactory.getInstance().getShape("L");
        l.diplay("灰色");
        AbstractBox o = BoxFactory.getInstance().getShape("O");
        o.diplay("灰色");
        AbstractBox a = BoxFactory.getInstance().getShape("I");
        a.diplay("红色");
        System.out.println(i==a);
    }
}

享元设计模式_第3张图片

你可能感兴趣的:(设计模式,设计模式,java,开发语言)