请设计一个多例模式的例子
时间: 2024-05-05 15:18:44 浏览: 7
好的,我可以给您一个多例模式的例子,比如说一个游戏中的玩家角色,假设我们有三种不同的角色类型:战士、法师和盗贼。我们可以使用多例模式来实现这个角色类,确保每个角色类型只有三个实例。
以下是示例代码:
```
public class Player {
private static final int MAX_PLAYERS = 3;
private static Map<String, Player> players = new HashMap<>();
private String type;
private Player(String type) {
this.type = type;
}
public static Player getInstance(String type) {
if (!players.containsKey(type)) {
if (players.size() >= MAX_PLAYERS) {
throw new RuntimeException("Max players reached for type: " + type);
}
players.put(type, new Player(type));
}
return players.get(type);
}
public void play() {
System.out.println("Playing as " + type);
}
}
```
在上面的代码中,我们使用了一个静态的 `players` 字典来存储已经创建的角色实例。当我们需要一个新的玩家实例时,如果该类型的实例数量已达到上限,则抛出异常,否则创建新的实例并将其添加到字典中。通过 `getInstance` 方法获取实例对象,通过 `play` 方法播放游戏。
我们可以使用以下代码来测试多例模式:
```
Player warrior1 = Player.getInstance("warrior");
Player warrior2 = Player.getInstance("warrior");
Player warrior3 = Player.getInstance("warrior");
Player mage1 = Player.getInstance("mage");
Player mage2 = Player.getInstance("mage");
Player mage3 = Player.getInstance("mage");
Player rogue1 = Player.getInstance("rogue");
Player rogue2 = Player.getInstance("rogue");
Player rogue3 = Player.getInstance("rogue");
warrior1.play(); // Playing as warrior
warrior2.play(); // Playing as warrior
warrior3.play(); // Playing as warrior
mage1.play(); // Playing as mage
mage2.play(); // Playing as mage
mage3.play(); // Playing as mage
rogue1.play(); // Playing as rogue
rogue2.play(); // Playing as rogue
rogue3.play(); // Playing as rogue
Player archer = Player.getInstance("archer"); // Throws exception: Max players reached for type: archer
```
以上代码演示了多例模式的使用,确保每个角色类型只有三个实例。