桥接模式的目的是将抽象与实现分离,使得它们可以独立地变化。下面是一个简单的Java桥接模式示例代码:
首先,定义一个接口,用于实现桥接模式:
public interface Operation {
void performOperation();
}
然后,定义一个实现该接口的类:
public class OperationAddition implements Operation {
@Override
public void performOperation() {
System.out.println("执行加法操作");
}
}
public class OperationSubtraction implements Operation {
@Override
public void performOperation() {
System.out.println("执行减法操作");
}
}
接下来,定义一个抽象的类,它也实现了Operation接口:
public abstract class OperationBridge {
protected Operation operation;
public OperationBridge(Operation operation) {
this.operation = operation;
}
public void performOperation() {
operation.performOperation();
}
}
定义具体的类,实现抽象的类:
public class AdditionBridge extends OperationBridge {
public AdditionBridge(OperationAddition operation) {
super(operation);
}
}
public class SubtractionBridge extends OperationBridge {
public SubtractionBridge(OperationSubtraction operation) {
super(operation);
}
}
最后,客户端代码使用具体的类来执行操作:
public class Client {
public static void main(String[] args) {
OperationBridge additionBridge = new AdditionBridge(new OperationAddition());
additionBridge.performOperation();
OperationBridge subtractionBridge = new SubtractionBridge(new OperationSubtraction());
subtractionBridge.performOperation();
}
}
运行结果如下:
执行加法操作
执行减法操作
通过这种方式,客户端只需要知道有一个统一的接口Operation,而无需关心具体的实现细节。当需要增加新的操作时,只需要添加一个新的实现类,而不需要修改现有的代码。这使得代码更加灵活,易于维护。