```mermaid classDiagram class ChessPiece { <<abstract>> +String color +display(int x, int y) } class WhiteChessPiece { +display(int x, int y) } class BlackChessPiece { +display(int x, int y) } class ChessPieceFactory { -static ChessPieceFactory instance -Map<String, ChessPiece> chessPieceMap +static getInstance() ChessPieceFactory +getChessPiece(String color) ChessPiece } class ChessBoard { -List<Move> moves +placePiece(String color, int x, int y) } class Move { +String color +int x +int y } ChessPiece <|-- WhiteChessPiece ChessPiece <|-- BlackChessPiece ChessPieceFactory --> ChessPiece ChessBoard --> ChessPieceFactory ChessBoard --> Move ```
package Tutorial13; import java.util.ArrayList; import java.util.List; class ChessBoard { private List<Move> moves = new ArrayList<>(); public void placePiece(String color, int x, int y) { ChessPiece piece = ChessPieceFactory.getInstance().getChessPiece(color); piece.display(x, y); moves.add(new Move(color, x, y)); } private class Move { String color; int x, y; Move(String color, int x, int y) { this.color = color; this.x = x; this.y = y; } } }
package Tutorial13; abstract class ChessPiece { protected String color; public abstract void display(int x, int y); } class WhiteChessPiece extends ChessPiece { public WhiteChessPiece() { this.color = "白"; } @Override public void display(int x, int y) { System.out.println("在位置 (" + x + ", " + y + ") 放置 " + color + " 棋子"); } } class BlackChessPiece extends ChessPiece { public BlackChessPiece() { this.color = "黑"; } @Override public void display(int x, int y) { System.out.println("在位置 (" + x + ", " + y + ") 放置 " + color + " 棋子"); } }
package Tutorial13; import java.util.HashMap; import java.util.Map; class ChessPieceFactory { private static ChessPieceFactory instance; private Map<String, ChessPiece> chessPieceMap; private ChessPieceFactory() { chessPieceMap = new HashMap<>(); } public static ChessPieceFactory getInstance() { if (instance == null) { instance = new ChessPieceFactory(); } return instance; } public ChessPiece getChessPiece(String color) { ChessPiece chessPiece = chessPieceMap.get(color); if (chessPiece == null) { if (color.equalsIgnoreCase("白")) { chessPiece = new WhiteChessPiece(); } else if (color.equalsIgnoreCase("黑")) { chessPiece = new BlackChessPiece(); } chessPieceMap.put(color, chessPiece); } return chessPiece; } }
package Tutorial13; public class GoGame { public static void main(String[] args) { ChessBoard board = new ChessBoard(); board.placePiece("白", 0, 0); board.placePiece("黑", 1, 1); board.placePiece("白", 2, 2); board.placePiece("黑", 3, 3); } }
标签:Tutorial13,String,软件设计,public,int,class,color,ChessPieceFactory From: https://www.cnblogs.com/muzhaodi/p/18540805