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<String,AbstractBox> 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{@Overridepublic String getShape() {return "I";}
}
package com.jmj.pattern.flyweight;public class LBox extends AbstractBox{@Overridepublic String getShape() {return "L";}
}
package com.jmj.pattern.flyweight;public class OBox extends AbstractBox{@Overridepublic 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);}
}