GoF 23个经典的设计模式7--结构模式之Bridge桥接模式(未完代续)

来源:互联网 发布:广发淘宝联名信用卡 编辑:程序博客网 时间:2024/05/02 09:18
 Bridge桥接模式: 分离实现和接口,使得实现能独立。
Decouple an abstraction from its implementation so that the two can vary independently. [GoF, p151]

 Bridge桥接模式和适配器模式看上去非常相似,他们的区别是Bridge模式是因为实现需要独立动态,而适配器是因为原来的实现已经存在,为了使用原来存在的实现而使用的。

其实Bridge模式是把原来在一起的类,分离开,在中间架做桥。

这图可以看出,我们只需要知道开关,并不需要怎么开风扇电灯电视就能一步完成。

pateximg7
Java代码也很简单:

客户只需要知道开关
package org.benewu.patterns.bridge;

public class Client {
    
public static void main(String[] args) {
        
        Switch sw 
= new Switch();
        sw.on();
        sw.off();
    }

}


开关定义开哪些电器
package org.benewu.patterns.bridge;

public class Switch {
    
private SwitchImpl impl = new SwitchImpl();
    
public void on(){
        impl.turnFanOn();
        impl.turnLightOn();
        impl.turnTVOn();
    }

    
public void off(){
        impl.turnFanOff();
        impl.turnLightOff();
        impl.turnTVOff();
    }

}


具体实现在另一个类完成,在这个类中做修改不会影响客户。
package org.benewu.patterns.bridge;

public class SwitchImpl {

    
public void turnLightOn(){
        System.out.println(
"turn light on");
    }

    
public void turnFanOn(){
        System.out.println(
"turn fan on");
    }

    
public void turnTVOn(){
        System.out.println(
"turn TV on");
    }

    
    
public void turnLightOff(){
        System.out.println(
"turn light off");
    }

    
public void turnFanOff(){
        System.out.println(
"turn fan off");
    }

    
public void turnTVOff(){
        System.out.println(
"turn TV off");
    }

    
}