桥接模式
桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
package birdge;
// 品牌
public interface Brand {
void info();
}
package birdge;
// 联想品牌
public class Lenovo implements Brand {
@Override
public void info() {
System.out.print("联想");
}
}
package birdge;
// 苹果品牌
public class Apple implements Brand {
@Override
public void info() {
System.out.print("苹果");
}
}
package birdge;
// 抽象的电脑类型
public class Computer {
// 组合,品牌 桥
protected Brand brand;
public Computer(Brand brand) {
this.brand = brand;
}
public void info() {
brand.info(); // 自带品牌
}
}
class Destop extends Computer {
public Destop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.print("台式机");
}
}
class Laptop extends Computer {
public Laptop(Brand brand) {
super(brand);
}
@Override
public void info() {
super.info();
System.out.print("笔记本");
}
}
package birdge;
public class Test {
public static void main(String[] args) {
// 苹果笔记本
Computer computer = new Laptop(new Apple());
computer.info();
// 联想台式机
Computer computer2 = new Destop(new Lenovo());
computer2.info();
}
}
好处分析:
- 桥接模式偶尔类似于多继承方案,但是多继承方案违背了类的单一职责原则,复用性比较差,类的个数也非常多,桥接模式是比多继承方案更好的解决方法,极大的减少了子类的个数,从而降低管理和维护的成本。
- 桥接模式提高了子系统的可扩充性,在两个变化维度中任意扩展一个维度,都不需要修改原有系统。符合开闭原则,就像一座桥,可以把两个变化的维度连接起来。
劣势分析:
- 桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。
- 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围具有一定的局限性。