旅游网站制作方法,蚌埠建设网站,做企业网站怎么接活,网站登陆口提交网站让我们以游戏开发中的棋类游戏#xff08;例如国际象棋#xff09;为例来展示享元模式的代码实现。在这个例子中#xff0c;棋子的类型是内部状态#xff0c;而棋子的位置是外部状态。
Java 代码示例
import java.util.HashMap;
import java.util.Map;// 享元接口
interf…让我们以游戏开发中的棋类游戏例如国际象棋为例来展示享元模式的代码实现。在这个例子中棋子的类型是内部状态而棋子的位置是外部状态。
Java 代码示例
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;}Overridepublic void move(int x, int y) {System.out.printf(Moving %s piece to (%d,%d).\n, color, x, y);}Overridepublic String getColor() {return color;}
}// 享元工厂
class ChessPieceFactory {private static final MapString, 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);// ... 其他棋子移动操作}
}在这个例子中ChessPieceFlyweight 接口定义了棋子的外部状态方法 move 和内部状态方法 getColor。ConcreteChessPiece 类实现了这个接口并持有内部状态 color它在棋子的生命周期中是不变的。
ChessPieceFactory 类是享元工厂它确保同一颜色的棋子只创建一次并在之后的请求中返回已创建的实例。这样即使在棋盘上有多个同色棋子实际上它们都是由同一个享元实例代表的。
客户端代码通过享元工厂获取棋子实例并多次调用 move 方法来改变棋子的位置这些位置信息作为外部状态在每次调用时传入。
这个例子展示了享元模式如何在需要大量相似对象的情况下减少内存消耗通过共享实例来避免重复创建相同或相似的对象。