设计模式:享元模式案例

时间:2024-04-10 17:24:24
import java.util.HashMap; import java.util.Map; // 享元接口 interface ChessPieceFlyweight { void move(int x, int y); // 外部状态:位置 String getColor(); // 内部状态:颜色 } // 具体享元类 class ConcreteChessPiece implements ChessPieceFlyweight { private final String color; // 内部状态 public ConcreteChessPiece(String color) { this.color = color; } @Override public void move(int x, int y) { System.out.printf("Moving %s piece to (%d,%d).\n", color, x, y); } @Override public String getColor() { return color; } } // 享元工厂 class ChessPieceFactory { private static final Map<String, ChessPieceFlyweight> pieces = new HashMap<>(); public static ChessPieceFlyweight getChessPiece(String color) { if (!pieces.containsKey(color)) { ChessPieceFlyweight piece = new ConcreteChessPiece(color); pieces.put(color, piece); } return pieces.get(color); } } // 客户端代码 public class FlyweightExample { public static void main(String[] args) { ChessPieceFlyweight whitePiece = ChessPieceFactory.getChessPiece("White"); ChessPieceFlyweight blackPiece = ChessPieceFactory.getChessPiece("Black"); // 棋子被多次移动到不同位置,但对象是共享的 whitePiece.move(1, 2); blackPiece.move(2, 3); whitePiece.move(4, 5); // ... 其他棋子移动操作 } }