1. 我们先来看一个产品图
这张图没有用桥接模式
2. 我们看看运用了桥接模式的产品图
用了桥接模式之后
3. 代码实现
品牌的接口
public interface Brand {
void info();
}
抽象的产品类
public abstract class Product {
//这里运用的就是组合的思想
protected Brand brand;
public Product(Brand brand) {
this.brand = brand;
}
public abstract void info();
}
品牌的实现类
public class Apple implements Brand {
@Override
public void info() {
System.out.print("苹果");
}
}
产品实现类
public class Computer extends Product {
public Computer(Brand brand) {
super(brand);
}
@Override
public void info() {
brand.info();
System.out.println("电脑");
}
}
测试类
public class Client {
public static void main(String[] args) {
Brand brand = new Apple();
Computer computer = new Computer(brand);
computer.info();
}
}
输出结果