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进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注