Bridging mode is the separation of things from their specific implementations so that they can change independently of each other. The purpose of bridging is to decouple abstraction from implementation so that they can change independently , like our usual JDBC bridge DriverManager, when JDBC connects to a database and switches between databases, The basic need not move too much code, even do not move, the reason is that JDBC provides a unified interface, each database provides its own implementation, with a program called Database driver to bridge the line. Let's take a look at the diagram:
Define the interface first:
Public interface Sourceable {public void method ();
Define two implementation classes, respectively:
public class SOURCESUB2 implements sourceable{@Overridepublic void method () {//TODO auto-generated method Stubsystem.out . println ("This is the second sub");}}
public class SourceSub1 implements sourceable{@Overridepublic void method () {//TODO auto-generated method Stubsystem.out . println ("This is the first sub");}}
Define a bridge that holds an instance of sourceable:
Public abstract class Bridge {private sourceable source;public void Method () {}public void SetSource (sourceable source) {th Is.source=source;} Public sourceable GetSource () {return this.source;}}
Because bridge is an abstract class, you must have subclass inheritance before you can use method methods.
public class Mybridge extends Bridge{public void method () {GetSource (). method ();}}
Test class:
public class Test {public static void main (string[] args) {Bridge bridge=new Mybridge ();/* Call First Object */sourceable Source1=n EW SourceSub1 (); Bridge.setsource (Source1); Bridge.method ();/* Call a second object */sourceable source2=new SourceSub2 (); Bridge.setsource (SOURCE2); Bridge.method ();}}
Output
This is the first sub!
This is the second sub!
In this way, the call of the bridge class is implemented, and the implementation class SOURCESUB1 and SOURCESUB2 of the docking port sourceable are realized. Next I draw a diagram, we should understand, because this diagram is the principle of our JDBC connection, there is a database learning basis, a combination of all understand.
Bridging mode (bridge)