桥接模式简介
- 桥接模式(bridge pattern)是一种将抽象与实现分离,使它们独立变化。然后利用组合关系来代替继承关系,大大的降低了抽象和实现的耦合度的设计模式。
- 实际使用: JDBC源码分析,定义了Driver接口,然后各个数据库厂商去实现Driver接口,
结构
- 1.抽象化角色(Abstraction):定义抽象类,并包含一个对实现化的引用。
- 2.扩展抽象化角色(Refined Abstraction):抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色的业务方法
- 3.实现化角色(Implementor):定义实现角色的接口,供扩展抽象化角色调用。
- 4.具体实现化角色(Concrete Implementor):给出实现化接口的具体实现。
优点
- 1.实现了抽象和实现部分的分离,提高了系统的灵活性,有助于系统进行分层设计。
- 2.桥接模式替代多层继承方案,可以减少子类的个数,降低系统的管理和维护成本。
UML图
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/9bd62cba8f224df4b89dd6e12885ef29.png)
具体实现
UML图
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/8b4f4facbfe043d6b5da5ef04fa2cadc.png)
代码实现
package com.xxliao.pattern.structure.bridge.demo;
public abstract class Phone {
private Brand brand;
public Phone(Brand brand) {
this.brand = brand;
}
public void call() {
brand.call();
}
}
package com.xxliao.pattern.structure.bridge.demo;
public class FoldedPhone extends Phone{
public FoldedPhone(Brand brand) {
super(brand);
}
public void call() {
super.call();
System.out.println("FoldedPhone");
}
}
package com.xxliao.pattern.structure.bridge.demo;
public class UpRightPhone extends Phone{
public UpRightPhone(Brand brand) {
super(brand);
}
public void call() {
super.call();
System.out.println("UpRightPhone");
}
}
package com.xxliao.pattern.structure.bridge.demo;
public interface Brand {
public abstract void call();
}
package com.xxliao.pattern.structure.bridge.demo;
public class HuaWeiBrand implements Brand {
@Override
public void call() {
System.out.println("HuaWei call...");
}
}
package com.xxliao.pattern.structure.bridge.demo;
public class MIBrand implements Brand{
@Override
public void call() {
System.out.println("MI call...");
}
}
package com.xxliao.pattern.structure.bridge.demo;
public class Client {
public static void main(String[] args) {
Phone phone1 = new FoldedPhone(new MIBrand());
phone1.call();
System.out.println("=========================================================");
Phone phone2 = new FoldedPhone(new HuaWeiBrand());
phone2.call();
System.out.println("=========================================================");
Phone phone3 = new UpRightPhone(new MIBrand());
phone3.call();
System.out.println("=========================================================");
Phone phone4 = new UpRightPhone(new HuaWeiBrand());
phone4.call();
System.out.println("=========================================================");
}
}
- 测试结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/e91878ea5a75418dbb65085125c14341.png)