桥接模式

因为这个模式网上有很多不恰当的例子,这里先引用百度百科的定义:桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
所以说桥接模式就是接口模式,一方调用接口,一方实现接口。还是百度上的示例代码:

public class Bridge {
    interface Implementor {//这里是抽象部分
        void Operation();
    }

    public static class RefinedAbstraction {//可以对这个再继承一个接口
        private Implementor implementor;

        public void setImplementor(Implementor implementor) {
            this.implementor = implementor;
        }

        public void Operation() {
            implementor.Operation();
        }
    }

    static class ConcreteImplementorA implements Implementor {
        public void Operation() {
            System.out.println("ConcreteImplementorA Operation");
        }
    }

    static class ConcreteImplementorB implements Implementor {
        public void Operation() {
            System.out.println("ConcreteImplementorB Operation");
        }
    }

    public static void main(String[] args) {
        RefinedAbstraction abstraction = new RefinedAbstraction();
        abstraction.setImplementor(new ConcreteImplementorA());
        abstraction.Operation();
        abstraction.setImplementor(new ConcreteImplementorB());//A和B的实现不同
        abstraction.Operation();
    }
}
输出:
ConcreteImplementorA Operation
ConcreteImplementorB Operation

看网上的很多例子,可能为了把事情说清楚,举得都是很平常的例子。但代码很复杂。其实我们只要知道这就是接口模式,我们就像平时用接口一样用就行了。其实面向对象有两个阶段,一是会用继承,第二就是会用接口。

觉得容易理解的话面向对象的23种设计模式点这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值