桥接模式
标签:设计模式

桥接模式

桥接模式是构造型的设计模式之一,基于类的最小设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是抽象与行为实现分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展。

1. 桥接模式中的角色及其职责

1.1 Client

桥接模式的使用者

就是后面使用的Main类

1.2 Abstraction

维护对行为实现(Implementor)的引用

Car

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/02
 */
public abstract class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public Engine getEngine() {
        return engine;
    }

    public abstract void installEngineForCar();
}

1.3 Refined Abstraction

Abstraction的子类

Bus

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/02
 */
public class Bus extends Car {

    public Bus(Engine engine) {
        super(engine);
    }

    @Override
    public void installEngineForCar() {
        System.out.print("Bus:");
        super.getEngine().installEngine();
    }
}

Taxi

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/02
 */
public class Taxi extends Car {
    public Taxi(Engine engine) {
        super(engine);
    }

    @Override
    public void installEngineForCar() {
        System.out.print("Taxi:");
        super.getEngine().installEngine();
    }
}

1.4 Implementor

行为实现类接口(Abstraction接口定义了基于Implementor接口的更高层次的操作)

Engine

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/02
 */
public interface Engine {
    public void installEngine();
}

1.5 Concrete Implementor

Implementor的子类

EngineA

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/02
 */
public class EngineA implements Engine{
    @Override
    public void installEngine() {
        System.out.println("install engine A");
    }
}

EngineB

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/02
 */
public class EngineB implements Engine {
    @Override
    public void installEngine() {
        System.out.println("install engine B");
    }
}

Main

package com.liuyao;

public class Main {

    public static void main(String[] args) {
        Engine enginea=new EngineA();
        Engine engineb=new EngineB();

        Car bus=new Bus(enginea);
        bus.installEngineForCar();

        Car taxi=new Taxi(engineb);
        taxi.installEngineForCar();
    }
}

//Bus:install engine A
//Taxi:install engine B
  • 2 min read

CONTRIBUTORS


  • 2 min read