2024/10/14
软件设计 石家庄铁道大学信息学院
实验13:享元模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解享元模式的动机,掌握该模式的结构;
2、能够利用享元模式解决实际问题。
[实验任务一]:围棋
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
实验要求:
1. 提交类图;
2. 提交源代码;
// 享元接口
interface Stone {
void move(Position position);
}
// 享元类
class ConcreteStone implements Stone {
private String color;
private Position position;
public ConcreteStone(String color) {
this.color = color;
}
@Override
public void move(Position position) {
this.position = position;
System.out.println(color + " stone moved to (" + position.getX() + ", " + position.getY() + ")");
}
public String getColor() {
return color;
}
}
// 位置类
class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
// 享元工厂类(单例模式 + 简单工厂模式)
class StoneFactory {
private static StoneFactory instance = new StoneFactory();
private Stone whiteStone;
private Stone blackStone;
private StoneFactory() {
whiteStone = new ConcreteStone("White");
blackStone = new ConcreteStone("Black");
}
public static StoneFactory getInstance() {
return instance;
}
public Stone getStone(String color) {
if ("White".equals(color)) {
return whiteStone;
} else if ("Black".equals(color)) {
return blackStone;
}
return null;
}
}
// 棋盘类
class GoBoard {
public void placeStone(String color, Position position) {
Stone stone = StoneFactory.getInstance().getStone(color);
stone.move(position);
}
}
// 围棋游戏类
class GoGame {
public void playGame() {
GoBoard board = new GoBoard();
board.placeStone("White", new Position(3, 3));
board.placeStone("Black", new Position(4, 4));
// 更多的走棋操作...
}
}
// 客户端代码
public class Main {
public static void main(String[] args) {
GoGame game = new GoGame();
game.playGame();
}
}
3.注意编程规范;
4.要求用简单工厂模式和单例模式实现享元工厂类的设计。

浙公网安备 33010602011771号