享元模式

实验13:享元模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解享元模式的动机,掌握该模式的结构;

2、能够利用享元模式解决实际问题。

试验任务一

设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。

类图

源代码

public interface GoBangPiece {
    void display(int x, int y);
}

public class BlackGoBangPiece implements GoBangPiece {
    @Override
    public void display(int x, int y) {
        System.out.println("Black piece placed at (" + x + ", " + y + ")");
    }
}

public class WhiteGoBangPiece implements GoBangPiece {
    @Override
    public void display(int x, int y) {
        System.out.println("White piece placed at (" + x + ", " + y + ")");
    }
}

public class GoBangPieceFactory {
    private static GoBangPieceFactory instance;

    // 私有构造函数
    private GoBangPieceFactory() {}

    // 获取实例的方法
    public static synchronized GoBangPieceFactory getInstance() {
        if (instance == null) {
            instance = new GoBangPieceFactory();
        }
        return instance;
    }

    // 存储已创建的享元对象
    private Map<String, GoBangPiece> pieces = new HashMap<>();

    // 创建或获取享元对象
    public GoBangPiece getGoBangPiece(String color) {
        if (!pieces.containsKey(color)) {
            switch (color) {
                case "W":
                    pieces.put("W", new WhiteGoBangPiece());
                    break;
                case "B":
                    pieces.put("B", new BlackGoBangPiece());
                    break;
                default:
                    throw new IllegalArgumentException("Invalid color");
            }
        }
        return pieces.get(color);
    }
}

public class Main {
    public static void main(String[] args) {
        // 获取享元工厂的单例实例
        GoBangPieceFactory factory = GoBangPieceFactory.getInstance();

        // 获取白棋和黑棋对象
        GoBangPiece whitePiece1 = factory.getGoBangPiece("W");
        GoBangPiece blackPiece1 = factory.getGoBangPiece("B");
        GoBangPiece whitePiece2 = factory.getGoBangPiece("W");

        // 在不同位置放置棋子
        whitePiece1.display(3, 4);
        blackPiece1.display(5, 6);
        whitePiece2.display(7, 8);

        // 检查是否是同一个对象
        System.out.println("whitePiece1 == whitePiece2: " + (whitePiece1 == whitePiece2));
    }
}

 

posted @   平安喜乐×  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示