美文网首页
Bridge Pattern(桥接模式)

Bridge Pattern(桥接模式)

作者: 杨志聪 | 来源:发表于2024-06-26 09:50 被阅读0次

解决的问题

开发一个电视机遥控器app,要求可以适配各种的电视机品牌(Sony、Samsung等)。遥控器分为基础版和高级版,基础版只能开关机,高级版可以切换频道。
可以这样设计:


普通方法.png

这样设计很好,有很好的拓展性,将来可以支持拓展更多的电视机品牌(XiaoMi、Huawei等),也可以支持拓展更多遥控器版本(例如,电影版,VIP版等)。
但是随着拓展越来越多,创建的类也会越来越多。这种情况,可以考虑使用Bridge Pattern(桥接模式)优化代码:


使用桥接模式.png

其实上面两种方式都可以,但是用桥接模式,代码会精简得多。

代码

Device:

package com.cong.designpattern.bridge;

public interface Device {
    public void trunOn();
    public void trunOff();
    public void setChannel(Number channel);
}

SonyDevice:

package com.cong.designpattern.bridge;

public class SonyDevice implements Device{
    @Override
    public void trunOn() {
        System.out.println("Trun on");
    }
    @Override
    public void trunOff() {
        System.out.println("Trun off");
    }
    @Override
    public void setChannel(Number channel) {
        System.out.println("Set channel to " + channel);
    }
}

RemoteControl:

package com.cong.designpattern.bridge;

public class RemoteControl {
    protected Device device;
    public RemoteControl(Device device) {
        this.device = device;
    }
    public void trunOn() {
        device.trunOn();
    }
    public void trunOff() {
        device.trunOff();
    }
}

AdvancedRemoteControl:

package com.cong.designpattern.bridge;

public class AdvancedRemoteControl extends RemoteControl {
    public AdvancedRemoteControl(Device device) {
        super(device);
    }
    public void setChannel(Number channel) {
        device.setChannel(channel);
    }
}

Test code:

SonyDevice sonyDevice = new SonyDevice();

RemoteControl  sonyRemoteControl = new RemoteControl(sonyDevice);
sonyRemoteControl.trunOn();
sonyRemoteControl.trunOff();

AdvancedRemoteControl sonyAdvancedRemoteControl = new AdvancedRemoteControl(sonyDevice);
sonyAdvancedRemoteControl.setChannel(1);

相关文章

  • 设计模式解析—桥接设计模式

    桥接模式(Bridge Pattern)定义和使用场景 定义桥接模式(Bridge Pattern):将抽象部分...

  • 10-桥接模式

    桥接模式-Bridge Pattern【学习难度:★★★☆☆,使用频率:★★★☆☆】 处理多维度变化——桥接模式(...

  • 设计模式-桥接模式

    设计模式-桥接模式 定义 桥接模式(Bridge Pattern)也称为桥梁模式、接口(Interface)模式或...

  • 结构型-桥接(Bridge)

    桥接(Bridge) [TOC] 定义 桥梁模式(Bridge Pattern)也叫做桥接模式,是一个比较简单的模...

  • 桥接模式(结构型)

    桥接模式[https://www.runoob.com/design-pattern/bridge-pattern...

  • Android 设计模式入门到精通之十二:桥接模式(Bridge

    桥接模式(Bridge Pattern,桥梁模式) 1. 概念 Decouple an abstraction f...

  • 桥接模式

    介绍 桥接模式(Bridge Pattern) 也称为桥梁模式,是结构型设计模式之一。桥接模式的作用就是连接 "两...

  • 结构型-Bridge

    桥接模式的原理解析 桥接模式,也叫作桥梁模式,英文是 Bridge Design Pattern。这个模式可以说是...

  • 桥接模式-Bridge Pattern

    在正式介绍桥接模式之前,我先跟大家谈谈两种常见文具的区别,它们是毛笔和蜡笔。假如我们需要大中小3种型号的画笔,能够...

  • 桥接模式(Bridge Pattern)

    桥接模式:使用桥接模式不只改变你的实现,也改变你的抽象。 桥接模式是将抽象和实现分离,使他们能够各自独立的变化。 ...

网友评论

      本文标题:Bridge Pattern(桥接模式)

      本文链接:https://www.haomeiwen.com/subject/pdxscjtx.html