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{
@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);
}
}
原文地址:https://blog.csdn.net/qq_53374893/article/details/134700365
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_36508.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。