今日报告

完成了软件设计实验13

 

实验13:享元模式

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

要求用简单工厂模式和单例模式实现享元工厂类的设计

GoPiece.java

复制代码
public class GoPiece {
    private String color;

    public GoPiece(String color) {
        this.color = color;
    }

    public void display(int x, int y) {
        System.out.println("Displaying " + color + " piece at position (" + x + ", " + y + ")");
    }
}
复制代码

GoPieceFactory.java

复制代码
public class GoPieceFactory {
    private static GoPiece whitePiece;
    private static GoPiece blackPiece;

    private GoPieceFactory() {
        // 私有构造函数,防止外部实例化
    }

    public static GoPiece getWhitePiece() {
        if (whitePiece == null) {
            whitePiece = new GoPiece("White");
        }
        return whitePiece;
    }

    public static GoPiece getBlackPiece() {
        if (blackPiece == null) {
            blackPiece = new GoPiece("Black");
        }
        return blackPiece;
    }
}
复制代码

GoGame.java

复制代码
public class GoGame {
    public static void main(String[] args) {
        // 使用享元工厂获取白棋和黑棋对象
        GoPiece whitePiece1 = GoPieceFactory.getWhitePiece();
        GoPiece blackPiece1 = GoPieceFactory.getBlackPiece();

        // 在不同位置显示多次
        whitePiece1.display(2, 3);
        blackPiece1.display(4, 5);

        // 创建第二个白棋对象并在不同位置显示
        GoPiece whitePiece2 = GoPieceFactory.getWhitePiece();
        whitePiece2.display(6, 7);
    }
}
复制代码

 

posted @   周+⑦  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示