(原创)认识设计模式-桥接

2015/03/14 设计模式

介绍

img

桥接的定义为:将抽象和实现解耦,使两者可以独立变化。

光看UML图,可以发现桥接模式和策略模式有点类似,只不过策略是行为型模式,桥接是结构型模式,但仔细发现桥接模式比策略模式多一个重定义抽象类,这个是干嘛用的?其实上面说了,抽象和实现可以独立变化的,也就是说,它比策略模式更灵活(虽然它们不属于同一类型的模式),策略模式相当于一个螺丝手柄加上一盒螺丝头,可以根据需要更换不同的螺丝头,而这个桥接模式相当于它不但可以更换不同的螺丝头,还可以使用电动手柄,因此,两边都可以变,因而适应性很强。

使用方式

	public interface Implementor {
	
	    public void doSomething();
	
	}
	
	public class ConcreteImplA implements Implementor {
	    
	    @Override
	    public void doSomething() {
	
	        System.out.println("ConcreteImplA doSomething ");
	
	    }
	
	}
	
	public class ConcreteImplB implements Implementor {
	    
	    @Override
	    public void doSomething() {
	
	        System.out.println("ConcreteImplB doSomething ");
	
	    }
	
	}
	
	public abstract class Abstraction {
	
	    protected Implementor mImplementor;
	
	    public Abstraction(Implementor impl)
	    {
	        mImplementor = impl;
	    }
	
	    abstract public void doSomething();
	
	}
	
	public class RefinedAbstraction extends Abstraction {
	
	    public RefinedAbstraction(Implementor impl)
	    {
	        super(impl);
	    }
	    @Override
	    public void doSomething() {
	
	        System.out.println("RefinedAbstraction doSomething ");
	        mImplementor.doSomething();
	
	    }
	}
	
	public class Main {
	
	    public static void main(String[] args) throws Exception {
	
	        Abstraction abstraction = new RefinedAbstraction(new ConcreteImplA());
	        abstraction.doSomething();
	
	        abstraction = new RefinedAbstraction(new ConcreteImplB());
	        abstraction.doSomething();
	
	    }
	}

结果如下:

RefinedAbstraction doSomething 
ConcreteImplA doSomething 
RefinedAbstraction doSomething 
ConcreteImplB doSomething 

总结

桥接模式使代码实现模块化编程,增加了代码的可复用性,关键是要把之间的接口抽象出来并封装,使抽象和实现都能独立。


知识共享许可协议
本作品采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可。

站内搜索

    撩我备注-博客

    joinee

    目录结构