桥接模式
是将抽象部分与它的实现部分分离,是他们都可以独立地变化。它是一种对象结构型模式,又称为炳体模式或者接口模式
- 优点
- 桥接模式偶尔类似于多继承,但是多继承方案违背了类的单一继承,复用性比较差,类的个数也非常多,桥接模式是比多继承方案更好的解决方法。极大的减少了子类的个数,从而降低管理和维护成本
- 桥接模式提高了系统放入可扩充性,在两个变化维度任意扩展一个维度,都不需要修改原有系统。符合开闭原则,就像一座桥,可以把两个变化的维度连接起来
- 缺点
- 桥接模式的引入会增加系统的理解与设计难度,由于聚合关系建立在抽象层,要求开发者针对抽象进行设计与编程
- 桥接模式要求正确识别出系统中的两个独立变化的维度,因此其使用范围具有一定的局限性
- 最佳实践场景
- Java语言提供JVM实现平台的无关性
- AWT中的Peer框架
- JDBC驱动程序也是桥接模式的应用之一
Brand
public interface Brand {
void info();
}
AppleBrand
public class XiaomiBrand implements Brand {
@Override
public void info() {
System.out.print("小米");
}
}
XiaomiBrand
public class AppleBrand implements Brand {
@Override
public void info() {
System.out.print("苹果");
}
}
电脑
public class Computer {
private Brand brand;
public Computer(Brand brand) {
this.brand = brand;
}
public void info(){
brand.info();
};
}
class Desktop extends Computer{
public Desktop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.println("台式电脑");
}
}
class Laptop extends Computer{
public Laptop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.println("笔记本电脑");
}
}
Test
public class Test {
public static void main(String[] args) {
Computer desktop = new Desktop(new AppleBrand());
desktop.info();
Computer laptop = new Laptop(new XiaomiBrand());
laptop.info();
}
}