享元模式
享元模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解享元模式的动机,掌握该模式的结构;
2、能够利用享元模式解决实际问题。
[实验任务一]:围棋
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
实验要求:
1.提交类图;
2.提交源代码;
3.注意编程规范;
4.要求用简单工厂模式和单例模式实现享元工厂类的设计。
源代码:
棋子类
public abstract class GoPiece {
protected String color;
public abstract void placePiece(int x, int y);
}
class WhitePiece extends GoPiece {
public WhitePiece() {
this.color = "白";
}
@Override
public void placePiece(int x, int y) {
System.out.println("放置" + color + "棋子在坐标 (" + x + ", " + y + ")");
}
}
class BlackPiece extends GoPiece {
public BlackPiece() {
this.color = "黑";
}
@Override
public void placePiece(int x, int y) {
System.out.println("放置" + color + "棋子在坐标 (" + x + ", " + y + ")");
}
}
享元工厂类
import java.util.HashMap;
public class GoPieceFactory {
private static final HashMap<String, GoPiece> pieces = new HashMap<>();
private GoPieceFactory() {}
public static GoPiece getPiece(String color) {
GoPiece piece = pieces.get(color);
if (piece == null) {
switch (color) {
case "白":
piece = new WhitePiece();
break;
case "黑":
piece = new BlackPiece();
break;
}
pieces.put(color, piece);
}
return piece;
}
}
public class GoGame {
public static void main(String[] args) {
GoPiece whitePiece1 = GoPieceFactory.getPiece("白");
whitePiece1.placePiece(2, 3);
GoPiece blackPiece1 = GoPieceFactory.getPiece("黑");
blackPiece1.placePiece(4, 5);
GoPiece whitePiece2 = GoPieceFactory.getPiece("白");
whitePiece2.placePiece(5, 6);
GoPiece blackPiece2 = GoPieceFactory.getPiece("黑");
blackPiece2.placePiece(6, 7);
System.out.println("白棋是否相同对象: " + (whitePiece1 == whitePiece2));
System.out.println("黑棋是否相同对象: " + (blackPiece1 == blackPiece2));
}
}