桥梁模式


桥梁模式

  • 桥梁模式:也叫作桥接模式,是个比较简单的模式,将抽象和实现解耦,使两者可以独立地变化(Decouple an abstraction from its implementation so that the two can vary independently)。
  • 桥梁模式的重点在解耦,我们先来看看桥梁模式的通用类图:

    • Abstraction抽象化角色:它的主要职责是定义出该角色的行为,同时保存一个对实现化角色的引用,该角色一般是抽象类;
    • Implementor实现化角色:它是接口或者抽象类,定义角色必须的行为和属性;
    • RefinedAbstraction修正抽象化角色:它引用实现化角色对抽象化角色进行修正;
    • ConcreteImplementor具体实现化角色:实现接口或抽象类定义的方法和属性。
  • public interface Implementor {
        public void doSomething();
        public void doAnything();
    }
    
    public class ConcreteImplementor implements Implementor{
    
        @Override
        public void doSomething() {
            // TODO Auto-generated method stub
            System.out.println("this is concreteImplementor doSomething");
        }
    
        @Override
        public void doAnything() {
            // TODO Auto-generated method stub
            System.out.println("this is concreteImplementor doAnything");
        }
    
    }
    
    public abstract class Abstraction {
        private Implementor imp;
        public Abstraction(Implementor imp){
            this.imp = imp;
        }
        public void request(){
            this.imp.doSomething();
        }
        public Implementor getImplementor(){
            return this.imp;
        }
    }
    
    public class RefinedAbstraction extends Abstraction{
    
        public RefinedAbstraction(Implementor imp) {
            super(imp);
            // TODO Auto-generated constructor stub
        }
        @Override
        public void request(){
            /**
             * 业务处理
             */
            super.request();
            super.getImplementor().doAnything();
        }
    }
    
    public class Client {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Abstraction abs = new RefinedAbstraction(new ConcreteImplementor());
            abs.request();
        }
    
    }
    View Code
桥梁模式的优点
  • 抽象和实现分离:为了解决继承的缺点而提出的设计模式,该模式下,实现可以不受抽象的约束,不用再绑定在一个固定的抽象层次上。
  • 优秀的扩充能力
  • 实现细节对客户透明,客户不用关系细节的实现,它已经由抽象层通过聚合关系完成了封装。
posted @ 2016-11-30 15:35  best.lei  阅读(298)  评论(0编辑  收藏  举报