实验13:享元模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解享元模式的动机,掌握该模式的结构;
2、能够利用享元模式解决实际问题。
[实验任务一]:围棋
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
实验要求:
1.提交类图;
2.提交源代码;
3.注意编程规范;
4.要求用简单工厂模式和单例模式实现享元工厂类的设计。
1.
2.import java.util.HashMap;
import java.util.Map;
// 棋子类
class GoStone {
private String color;
public GoStone(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
// 简单工厂类
class GoStoneFactory {
public GoStone getStone(String color) {
return new GoStone(color);
}
}
// 单例工厂类
class SingletonGoStoneFactory {
private static SingletonGoStoneFactory instance;
private Map<String, GoStone> stoneMap = new HashMap<>();
private SingletonGoStoneFactory() {}
public static SingletonGoStoneFactory getInstance() {
if (instance == null) {
instance = new SingletonGoStoneFactory();
}
return instance;
}
public GoStone getStone(String color) {
if (!stoneMap.containsKey(color)) {
stoneMap.put(color, new GoStone(color));
}
return stoneMap.get(color);
}
}
// 棋盘类
class GoBoard {
private int size;
private GoStone[][] board;
public GoBoard(int size) {
this.size = size;
this.board = new GoStone[size][size];
}
public void placeStone(GoStone stone, int x, int y) {
if (x >= 0 && x < size && y >= 0 && y < size) {
board[x][y] = stone;
}
}
public void printBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] == null) {
System.out.print(". ");
} else {
System.out.print(board[i][j].getColor() + " ");
}
}
System.out.println();
}
}
}
// 客户端代码
public class GoGame {
public static void main(String[] args) {
int boardSize = 9; // 棋盘大小
GoBoard board = new GoBoard(boardSize);
GoStoneFactory factory = new GoStoneFactory();
GoStone blackStone = factory.getStone("black");
GoStone whiteStone = factory.getStone("white");
board.placeStone(blackStone, 0, 0);
board.placeStone(whiteStone, 1, 1);
board.printBoard();
// 使用单例工厂
SingletonGoStoneFactory singletonFactory = SingletonGoStoneFactory.getInstance();
GoStone blackStoneSingleton = singletonFactory.getStone("black");
GoStone whiteStoneSingleton = singletonFactory.getStone("white");
board.placeStone(blackStoneSingleton, 2, 2);
board.placeStone(whiteStoneSingleton, 3, 3);
board.printBoard();
}
}