java 外观模式 例子
时间: 2023-05-20 17:00:56 浏览: 61
外观模式是一种结构型设计模式,它提供了一个简单的接口,隐藏了一组复杂的子系统接口,使得客户端能够更加方便地使用这些子系统。
以下是一个 Java 外观模式的例子:
```
// 外观类
public class Computer {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public Computer() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
public void startComputer() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}
}
// 子系统类
public class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}
public class Memory {
public void load(long position, byte[] data) { ... }
}
public class HardDrive {
public byte[] read(long lba, int size) { ... }
}
```
在这个例子中,`Computer` 类是外观类,它封装了一组复杂的子系统接口,包括 `CPU`、`Memory` 和 `HardDrive`。客户端只需要调用 `Computer` 类的 `startComputer` 方法,就可以启动计算机了。在 `startComputer` 方法中,`Computer` 类会调用子系统的接口,完成计算机的启动过程。
注意,这个例子只是一个简单的示例,实际上外观模式可以应用于更加复杂的系统中。