[实验任务一]:围棋
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
实验要求:
1. 提交类图;
2.提交源代码;
3.注意编程规范;
4.要求用简单工厂模式和单例模式实现享元工厂类的设计。
package Xiang; public class BlackChessPiece implements ChessPiece { @Override public void display(int x, int y) { System.out.println("在位置(" + x + ", " + y + ") 显示黑棋"); // 显示黑棋的具体实现 } } package Xiang; public interface ChessPiece { void display(int x, int y); // 在棋盘的特定位置显示棋子 } package Xiang; import java.util.HashMap; import java.util.Map; public class ChessPieceFactory { private static Map<String, ChessPiece> pieces = new HashMap<>(); public static ChessPiece getChessPiece(String color) { ChessPiece piece = pieces.get(color); if (piece == null) { if (color.equalsIgnoreCase("white")) { piece = new WhiteChessPiece(); } else if (color.equalsIgnoreCase("black")) { piece = new BlackChessPiece(); } pieces.put(color, piece); } return piece; } } package Xiang; public class WhiteChessPiece implements ChessPiece { @Override public void display(int x, int y) { System.out.println("在位置(" + x + ", " + y + ") 显示白棋"); // 显示白棋的具体实现 } } package Xiang; public class Main { public static void main(String[] args) { ChessPiece white = ChessPieceFactory.getChessPiece("white"); white.display(1, 2); ChessPiece black = ChessPieceFactory.getChessPiece("black"); black.display(3, 4); ChessPiece whiteAgain = ChessPieceFactory.getChessPiece("white"); whiteAgain.display(5, 6); } }
标签:享元,13,ChessPiece,int,display,white,piece,public,Tutorial From: https://www.cnblogs.com/JJTyyds/p/17831495.html