有一款游戏软件,分为与电脑对战和与人对战两种玩法,而每种玩法又分简易操作和复杂操作两种,假设现在需要你根据选择的情况创建具体的游戏对象,你会采用抽象工厂模式进行设计,Java代码演示
时间: 2024-05-01 18:18:48 浏览: 5
当然,我非常了解抽象工厂模式,以下是Java代码演示:
首先,我们需要定义两个抽象产品接口:Game和Operation。
```java
public interface Game {
void play();
}
public interface Operation {
void operate();
}
```
然后,我们定义两个具体产品类:ComputerGame和HumanGame,以及其对应的简易操作和复杂操作类。
```java
public class ComputerGame implements Game {
@Override
public void play() {
System.out.println("与电脑对战的游戏");
}
}
public class HumanGame implements Game {
@Override
public void play() {
System.out.println("与人对战的游戏");
}
}
public class SimpleOperation implements Operation {
@Override
public void operate() {
System.out.println("简易操作");
}
}
public class ComplexOperation implements Operation {
@Override
public void operate() {
System.out.println("复杂操作");
}
}
```
接着,我们定义抽象工厂接口:GameFactory。
```java
public interface GameFactory {
Game createGame();
Operation createOperation();
}
```
最后,我们定义两个具体工厂类:ComputerGameFactory和HumanGameFactory,分别用于创建与电脑对战和与人对战的游戏对象。
```java
public class ComputerGameFactory implements GameFactory {
@Override
public Game createGame() {
return new ComputerGame();
}
@Override
public Operation createOperation() {
return new ComplexOperation();
}
}
public class HumanGameFactory implements GameFactory {
@Override
public Game createGame() {
return new HumanGame();
}
@Override
public Operation createOperation() {
return new SimpleOperation();
}
}
```
使用抽象工厂模式,我们可以轻松地根据选择的情况创建具体的游戏对象,比如:
```java
// 选择与电脑对战的复杂操作游戏
GameFactory factory = new ComputerGameFactory();
Game game = factory.createGame();
Operation operation = factory.createOperation();
game.play(); // 输出:与电脑对战的游戏
operation.operate(); // 输出:复杂操作
```