概念:将抽象和实现解耦,使得两者可以独立地变化。
- 抽象角色,定义要实现的操作。
- 修正的抽象角色,继承抽象角色。
- 接口或抽象类Implementor,定义要实现的操作。
- 具体的操作类。
以一个生产手机的例子来帮助大家理解。
java
// 实现部分:内存模块接口
interface MemoryModule {
int getMemoryCapacity(); // 获取内存容量
void performMemoryOperation(); // 示例方法,执行特定内存操作
}
// 具体实现:华为内存模块
class HuaweiMemory implements MemoryModule {
private final int memoryCapacity;
public HuaweiMemory(int capacity) {
this.memoryCapacity = capacity;
}
@Override
public int getMemoryCapacity() {
return memoryCapacity;
}
@Override
public void performMemoryOperation() {
System.out.println("Performing a Huawei-specific memory operation.");
}
}
// 具体实现:小米内存模块
class XiaomiMemory implements MemoryModule {
private final int memoryCapacity;
public XiaomiMemory(int capacity) {
this.memoryCapacity = capacity;
}
@Override
public int getMemoryCapacity() {
return memoryCapacity;
}
@Override
public void performMemoryOperation() {
System.out.println("Performing a Xiaomi-specific memory operation.");
}
}
// 抽象部分:手机基类
abstract class Phone {
protected MemoryModule memoryModule;
public Phone(MemoryModule memoryModule) {
this.memoryModule = memoryModule;
}
public abstract String getModelName(); // 获取手机型号
public int getMemoryCapacity() {
return memoryModule.getMemoryCapacity();
}
public void performMemoryOperation() {
memoryModule.performMemoryOperation();
}
}
// 具体抽象:华为手机
class HuaweiPhone extends Phone {
public HuaweiPhone(MemoryModule memoryModule) {
super(memoryModule);
}
@Override
public String getModelName() {
return "Huawei P50 Pro";
}
}
// 具体抽象:小米手机
class XiaomiPhone extends Phone {
public XiaomiPhone(MemoryModule memoryModule) {
super(memoryModule);
}
@Override
public String getModelName() {
return "Xiaomi Mi 11";
}
}
// 客户端代码
public class BridgePatternDemo {
public static void main(String[] args) {
// 创建内存模块实例
MemoryModule huawei6GB = new HuaweiMemory(6);
MemoryModule huawei8GB = new HuaweiMemory(8);
MemoryModule xiaomi6GB = new XiaomiMemory(6);
MemoryModule xiaomi8GB = new XiaomiMemory(8);
// 创建不同内存配置的手机实例
Phone huaweiPhone6GB = new HuaweiPhone(huawei6GB);
Phone huaweiPhone8GB = new HuaweiPhone(huawei8GB);
Phone xiaomiPhone6GB = new XiaomiPhone(xiaomi6GB);
Phone xiaomiPhone8GB = new XiaomiPhone(xiaomi8GB);
// 输出手机型号及内存信息
System.out.printf("Phone: %s, Memory: %d GB%n", huaweiPhone6GB.getModelName(), huaweiPhone6GB.getMemoryCapacity());
System.out.printf("Phone: %s, Memory: %d GB%n", huaweiPhone8GB.getModelName(), huaweiPhone8GB.getMemoryCapacity());
System.out.printf("Phone: %s, Memory: %d GB%n", xiaomiPhone6GB.getModelName(), xiaomiPhone6GB.getMemoryCapacity());
System.out.printf("Phone: %s, Memory: %d GB%n", xiaomiPhone8GB.getModelName(), xiaomiPhone8GB.getMemoryCapacity());
// 执行内存操作
huaweiPhone6GB.performMemoryOperation();
huaweiPhone8GB.performMemoryOperation();
xiaomiPhone6GB.performMemoryOperation();
xiaomiPhone8GB.performMemoryOperation();
}
}
如果大家需要视频版本的讲解,欢迎关注我的B站:
十一、设计模式之桥接模式讲解