2024.11.12
设计模式实验十三
软件设计 石家庄铁道大学信息学院
实验13:享元模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解享元模式的动机,掌握该模式的结构;
2、能够利用享元模式解决实际问题。
[实验任务一]:围棋
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
实验要求:
1. 提交类图;
2.提交源代码;
import java.util.Hashtable;
// Coordinates.java
class Coordinates {
private int x;
private int y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
// Chess.java
abstract class Chess {
public abstract String getColor();
public void locate(Coordinates coordinates) {
System.out.println(getColor() + " chess piece located at (" + coordinates.getX() + ", " + coordinates.getY() + ")");
}
}
// BlackChess.java
class BlackChess extends Chess {
@Override
public String getColor() {
return "Black";
}
}
// WhiteChess.java
class WhiteChess extends Chess {
@Override
public String getColor() {
return "White";
}
}
// ChessFactory.java
class ChessFactory {
private static ChessFactory instance = new ChessFactory();
private Hashtable<String, Chess> ht;
private ChessFactory() {
ht = new Hashtable<>();
ht.put("black", new BlackChess());
ht.put("white", new WhiteChess());
}
public static ChessFactory getInstance() {
return instance;
}
public Chess getChess(String color) {
return ht.get(color.toLowerCase());
}
}
// TestChess.java
public class TestChess {
public static void main(String[] args) {
ChessFactory factory = ChessFactory.getInstance();
Chess black1 = factory.getChess("black");
black1.locate(new Coordinates(1, 1));
Chess white1 = factory.getChess("white");
white1.locate(new Coordinates(2, 2));
Chess black2 = factory.getChess("black");
black2.locate(new Coordinates(3, 3));
Chess white2 = factory.getChess("white");
white2.locate(new Coordinates(4, 4));
// 检查是否为同一实例
System.out.println("black1 == black2: " + (black1 == black2));
System.out.println("white1 == white2: " + (white1 == white2));
}
}
3.注意编程规范;
4.要求用简单工厂模式和单例模式实现享元工厂类的设计。