Design mode: Bridge -- bridge mode

Bridge mode: separate the transaction and specific behavior, and realize the corresponding implementation of the interface through bridge call

Bridge mode is to separate things from their concrete realization, so that they can change independently. The purpose of bridging is to decouple abstraction and implementation, so that they can change independently. Like our commonly used JDBC bridge DriverManager, when JDBC connects to the database, it basically does not need to move too much code or even move nothing. The reason is that JDBC provides a unified interface, and each database provides its own implementation A program called database driver can bridge. Let's look at the diagram:

By calling the Bridge class, the implementation classes SourceSub1 and SourceSub2 of the interface Sourceable are called;

 

Code: different engines are installed in different vehicles. Engine is called by reference to engine results to realize specific calls, such as 2000cc engine installation.

package com.atguigu.bridge.bridgeDemo1;

/**
 * Engine interface
 */
interface Engine {
    public void installEngine();
}

//2000cc engine installation
class Engine2000 implements Engine {
    @Override
    public void installEngine() {
        System.out.println("Install 2000 cc engine");
    }
}


//2200cc engine installation
class Engine2200 implements Engine {
    @Override
    public void installEngine() {
        System.out.println("Install 2200 cc engine");
    }
}

abstract class Car {
    private Engine engine;

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

    public Engine getEngine() {
        return engine;
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public abstract void installEngine();
}


class Bus extends Car {


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

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

class Jeep extends Car {

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

    @Override
    public void installEngine() {
        System.out.print("Jeep: ");
        this.getEngine().installEngine();
    }
}

public class MainClass {
    public static void main(String[] args) {
        Engine engine = new Engine2000();

        Car car = new Bus(engine);
        car.installEngine();

        Engine engine1 = new Engine2200();
        Car car1 = new Jeep(engine1);
        car1.installEngine();

    }
}

//Output results:
Bus: Install 2000 cc engine
Jeep: Install 2200 cc engine

Test results:

 

 

This figure is the principle of our JDBC connection

Tags: JDBC Database

Posted on Wed, 06 Nov 2019 13:17:28 -0800 by Calimero