java设计模式之——桥接(Bridge)模式

设计模式之——桥接(Bridge)模式

桥接模式定义

桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interfce)模式。

桥接模式的优点

  1. 扩展能力强。

桥接模式的缺点

  1. 增加了系统的理解与设计难度。

桥接模式的实现

定义一个接口

/**
 * @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();
    }
}

运行结果

扩展实例被调用了
我在做事情

桥接模式的使用场景

  1. 系统需要在抽象化和具体化角色之间增加更多的功能。
  2. 系统不希望使用多层次继承。
  3. 类存在两个独立变化的维度,且这两个维度都需要进行扩展。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值