Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/40008711
Bridging mode (bridge): separate things from their specific implementations (abstraction and decoupling) so that they can change independently. Assuming your computer is a dual system (WinXP, Win7), and all 4 databases are installed, such as MySQL, Oracle, SQL Server, DB2, then you have a 2*4 option to connect to the database. According to the usual wording, I want to write 2*4 class, but the use of bridge mode, you just write 2+4 class, you can see that the bridge mode is actually a kind of n*m into the n+m combination of ideas.
First, UML modeling:
Second, the Code implementation
/** * Bridging mode (BRIDGE): separate things from their specific implementations (abstraction and decoupling) so that they can change independently of each other. * * Assuming your computer is a dual system (WinXP, Win7), and all 4 databases of MySQL, Oracle, SQL Server, DB2 are installed * * then you have 2*4 option to connect to the database. According to the usual wording, I want to write 2*4 class, but using the bridge mode, you just write 2+4 class * * Can see that the bridge mode is actually a kind of n*m into the n+m combination of ideas. */interface Driver {public void method (); Class Mysqldriver implements Driver {@Overridepublic void method () {System.out.println ("use MySQL Driver to connection db. .. \ n ");}} Class Oracledriver implements Driver {@Overridepublic void method () {SYSTEM.OUT.PRINTLN ("Use Oracle Driver to connection D B...\n ");}} /** * Here you can also write SQLServerDriver, db2driver ... */abstract class computer {public abstract void connection (Driver Driver);} Class WinXP extends computer {@Overridepublic void connection (Driver Driver) {System.out.println ("WinXP computer"); Driver.method ();}} Class Win7 extends computer {@Overridepublic void connection (Driver Driver) {System.out.println ("Win7 computer"); Driver.method ();}} /** * Client Test class * * @author Leo */public class Test {public static void main (string[] args) {/*** First combination: WinXP using MySQL driver connection database */computer winxp = new WinXP (); Winxp.connection (new Mysqldriver ());/** * The second combination: Win7 uses the MySQL driver to connect to the database */computer win7 = new Win7 (); Win7.connection (new Mysqldriver ());/** * Third combination: WinXP uses the Oracle drive to connect to the database */computer CWINXP = new WinXP (); Cwinxp.connection (new Oracledriver ());/** * Fourth combination: WinXP using Oracle Driver Connection database */computer cwin7 = new Win7 (); Cwin7.connection (new Oracledriver ());}}
Iii. Summary
The core idea of bridging is: to decouple abstraction from realization, so that they can change independently.
Java Design Patterns Rookie series (17) modeling and implementation of bridging mode