设计模式之——桥接(Bridge)模式
桥接模式定义
桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interfce)模式。
桥接模式的优点
- 扩展能力强。
桥接模式的缺点
- 增加了系统的理解与设计难度。
桥接模式的实现
定义一个接口
/**
* @ClassName DemoInterface
* @Description TODO
* @Author mamingcong
* @Date 2020/6/10 13:14
* @Version 1.0
*/
public interface DemoInterface {
public void doSth();
}
实现这个接口
/**
* @ClassName DemoInterfaceImpl
* @Description TODO
* @Author mamingcong
* @Date 2020/6/10 13:15
* @Version 1.0
*/
public class DemoInterfaceImpl implements DemoInterface{
@Override
public void doSth() {
System.out.println("我在做事情");
}
}
定义一个抽象类
/**
* @ClassName DemoAbstract
* @Description TODO
* @Author mamingcong
* @Date 2020/6/10 13:16
* @Version 1.0
*/
public abstract class DemoAbstract {
protected DemoInterface demoInterface;
public DemoAbstract(DemoInterface demoInterface) {
this.demoInterface = demoInterface;
}
public abstract void doSth();
}
继承这个抽象类
/**
* @ClassName DemoAbstractImpl
* @Description TODO
* @Author mamingcong
* @Date 2020/6/10 13:18
* @Version 1.0
*/
public class DemoAbstractImpl extends DemoAbstract {
public DemoAbstractImpl(DemoInterface demoInterface) {
super(demoInterface);
}
@Override
public void doSth() {
System.out.println("扩展实例被调用了");
demoInterface.doSth();
}
}
测试
/**
* @ClassName Test
* @Description TODO
* @Author mamingcong
* @Date 2020/6/10 13:21
* @Version 1.0
*/
public class Test {
public static void main(String[] args) {
DemoInterface demoInterface = new DemoInterfaceImpl();
DemoAbstract demoAbstract = new DemoAbstractImpl(demoInterface);
demoAbstract.doSth();
}
}
运行结果
扩展实例被调用了
我在做事情
桥接模式的使用场景
- 系统需要在抽象化和具体化角色之间增加更多的功能。
- 系统不希望使用多层次继承。
- 类存在两个独立变化的维度,且这两个维度都需要进行扩展。