设计模式——桥接模式

281 阅读1分钟

最新修改已更新到github

桥接模式_将类的功能层次结构和类的实现结构分离

/**
 * 类的功能层次
 * @author maikec
 * @date 2019/5/12
 */
public class Abstraction {
    private BaseImplementer implementer;
    public Abstraction(BaseImplementer implementer){
        this.implementer = implementer;
    }
    public void firstStep(){
        implementer.sayFirst();
    }
    public void secondStep(){
        implementer.saySecond();
    }
    public void thirdStep(){
        implementer.sayThird();
    }

    public void doSingleThing(){
        firstStep();
        secondStep();
        thirdStep();
    }
}

/**
 * 类的功能层次
 * @author maikec
 * @date 2019/5/12
 */
public class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(ConcreteImplementer implementer) {
        super( implementer );
    }

    public void doMultipleStep(){
        firstStep();
        for (int i = 0; i < 3; i++) {
            secondStep();
        }
        thirdStep();
    }
}

/**
 * 类的实现结构
 * @author maikec
 * @date 2019/5/12
 */
public abstract class BaseImplementer {
    /**
     * 第一步
     */
    protected abstract void sayFirst();
    /**
     * 第二步
     */
    protected abstract void saySecond();
    /**
     * 第三步
     */
    protected abstract void sayThird();

}

/**
 * 类的实现结构
 * @author maikec
 * @date 2019/5/12
 */
public class ConcreteImplementer extends BaseImplementer {
    @Override
    protected void sayFirst() {
        System.out.println( "ConcreteImplementer First" );
    }

    @Override
    protected void saySecond() {
        System.out.println( "ConcreteImplementer Second" );
    }

    @Override
    protected void sayThird() {
        System.out.println( "ConcreteImplementer Third" );
    }
}

/**
 * @author maikec
 * @date 2019/5/12
 */
public class BridgeDemo {
    public static void main(String[] args) {
        BaseImplementer implementer = new ConcreteImplementer();
        Abstraction abstraction = new Abstraction( implementer );
        abstraction.doSingleThing();
        System.out.println( "====" );
        RefinedAbstraction refinedAbstraction = new RefinedAbstraction( (ConcreteImplementer) implementer );
        refinedAbstraction.doMultipleStep();
    }
}

附录

github.com/maikec/patt… 个人GitHub设计模式案例

声明

引用该文档请注明出处