今日报告
完成了软件设计实验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); } }

浙公网安备 33010602011771号