java
package com.jmj.pattern.flyweight;
public abstract class AbstractBox {
//获取图形的方法
public abstract String getShape();
//显示图形及颜色
public void diplay(String color){
System.out.println("方块形状:"+getShape()+",颜色:"+color);
}
}
java
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);
}
}
java
package com.jmj.pattern.flyweight;
public class IBox extends AbstractBox{
@Override
public String getShape() {
return "I";
}
}
java
package com.jmj.pattern.flyweight;
public class LBox extends AbstractBox{
@Override
public String getShape() {
return "L";
}
}
java
package com.jmj.pattern.flyweight;
public class OBox extends AbstractBox{
@Override
public String getShape() {
return "O";
}
}
java
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);
}
}