设计模式(十一) : 结构型模式--桥梁模式

桥梁模式的用意是:将抽象化和实现化惊醒脱耦,使得两者可以独立的变化。所谓脱耦就是将抽象化和实现化之间的耦合解脱开,也就是强关联变成若关联。

强关联就是在编译期就已经确立的,无法在运行时改变;弱关联就是可以动态的确定并且运行期可以改变的关联。继承是强关联,合成、聚合是弱关联。

类图:

设计模式(十一) : 结构型模式--桥梁模式

示意性代码:

package com.javadesignpattern.Bridge;



public interface Implementor {

    

    void operation();



}
package com.javadesignpattern.Bridge;



public class ConcreteImplementor1 implements Implementor {



    public void operation() {

        // TODO Auto-generated method stub

        System.out.println(ConcreteImplementor1.class + ": operation function");

        //System.out.println("Customer");

    }



}
package com.javadesignpattern.Bridge;



public class ConcreteImplementor2 implements Implementor{



    public void operation() {

        // TODO Auto-generated method stub

        System.out.println(ConcreteImplementor2.class + ": operation function");

        //System.out.println("Thing");

    }



}
package com.javadesignpattern.Bridge;



public abstract class Abstraction {

    

    Implementor impl;

    

    public Abstraction(Implementor impl){

        this.impl = impl;

    }

    

    public void operation(){

        impl.operation();

        

        System.out.println(Abstraction.class + " : operation function");

    }



}
package com.javadesignpattern.Bridge;



public class RedefinedAbstraction extends Abstraction {



    public RedefinedAbstraction(Implementor impl) {

        super(impl);

        // TODO Auto-generated constructor stub

    }

    

    public void operation(){

        super.operation();

        System.out.println(RedefinedAbstraction.class + " : operation function");

        //System.out.println("Car");

    }





}
package com.javadesignpattern.Bridge;



public class Client {

    

    public static void main(String[] args){

        Abstraction abs = new RedefinedAbstraction(new ConcreteImplementor1());

        abs.operation();

    }



}

在网上看到一个例子解释这个的,我觉得蛮好的,mark一下:http://alaric.iteye.com/blog/1918381

 

 

《java与模式》里面,讲到的jdbc驱动器的例子。drivermanager根据url(定义响应的数据库的url)得到具体的实现。

你可能感兴趣的:(设计模式)