Bridge pattern in Java design mode

Source: Internet
Author: User

I. Overview
Separate the abstract part from its implementation, so that they can all change independently. It is an object-structured pattern, also known as a handle body (Handle and body) mode.

Second, the application scenario
Handle multi-dimensional changes.
Business Scenario: A feature that transforms data in a database into a variety of file formats, such as TXT, XML, and PDF, while supporting the reading of many different types of databases. It can be designed using the bridging mode.
Here are two dimensions: different file formats and different database types. Such as:

Third, UML class diagram
Bridge mode common structure diagram:

For the above business scenario-bridging Mode-Example map:

Iv. participants
①abstraction (abstract Class): an interface for defining an abstract class, which is generally an abstract class rather than an interface, which defines an object of type Implementor (Implementing a class interface) and can maintain the object, which has an association with implementor. It can contain either an abstract business method or a specific business method.
②refinedabstraction (Augmented abstract Class): Expands an interface defined by abstraction, typically no longer an abstract class but a concrete class that implements an abstract business method declared in abstraction. The business methods defined in Implementor can be called in refinedabstraction.
③implementor (Implementation class interface): Define the interface of the implementation class, this interface does not have to be exactly the same as the abstraction interface, in fact, the two interfaces can be completely different, in general, the Implementor interface only provides basic operations, The interfaces defined by abstraction may do more and more complex operations. These basic operations are declared by the Implementor interface, and the specific implementation is given to its subclasses. By associating relationships, not only do you have your own methods in abstraction, you can also call the methods defined in Implementor and use association relationships to override inheritance relationships.
④concreteimplementor (Concrete implementation Class): the implementation of the Implementor interface, in different concreteimplementor to provide a different implementation of basic operations, when the program runs, The Concreteimplementor object replaces its parent class object, which is provided to the abstract class for specific business operation methods.

V. Use case learning < using business scenarios in the scenario as code design >
1. JDBC Driver Connection Management class: Jdbcdrivermanager.java

/** * JDBC Driver Connection Management class * @author [email protected] * */ Public  class jdbcdrivermanager {     PublicStringconnectandreadoracle(){//Simulate the code that connects the Oracle databaseSystem.out.println ("Successfully connected to Oracle database");//mode omits code that gets content from the databaseString content ="The content was successfully read from the Oracle database";returnContent } PublicStringConnectandreadmysql(){//Simulate the code that connects MySQL databaseSystem.out.println ("Successfully connected to MySQL database");//mode omits code that gets content from the databaseString content ="The content was successfully read from the MySQL database";returnContent } PublicStringConnectandreadsqlserver(){//Impersonate the code that connects the SQL Server databaseSystem.out.println ("Successfully connected to SQL Server database");//mode omits code that gets content from the databaseString content ="The content was successfully read from the SQL Server database";returnContent }}

2. < role: Implementing class Interface > Fileexportimpl.java

/** * 获取文件内容、连接数据库来源接口 * @author [email protected] * */publicinterface FileExportImpl {    /**     * 读取数据库中的内容     * @param jdbcDriver     * @return     */    publicreadContent();}

3, < role: specific implementation of the class > Fileexportfromoracle.java

/** * 从Oracle数据库获取内容 * @author [email protected] * */publicclass FileExportFromOracle implements FileExportImpl {    @Override    publicreadContent() {        new JdbcDriverManager();        return jdbcDriver.connectAndReadOracle();    }}

4, < role: specific implementation of the class > Fileexportfrommysql.java

/** * 从MySql数据库获取内容 * @author [email protected] * */publicclass FileExportFromMySql implements FileExportImpl {    @Override    publicreadContent() {        new JdbcDriverManager();        return jdbcDriver.connectAndReadMySql();    }}

5, < role: specific implementation of the class > Fileexportfromsqlserver.java

/** * 从Sql Server数据库获取内容 * @author [email protected] * */publicclass FileExportFromSqlServer implements FileExportImpl {    @Override    publicreadContent() {        new JdbcDriverManager();        return jdbcDriver.connectAndReadSqlServer();    }}

6. < role: abstract class > Fileexportabstraction.java

/** * 文件格式导出 抽象类 * @author [email protected] * */publicabstractclass FileExportAbstraction {    protected FileExportImpl fileSouce;    publicvoidsetFileSource(FileExportImpl fileSouce){        this.fileSouce = fileSouce;    }    publicabstractvoidexportFile();}

7. < role: Expand abstract Class > Txtfileexport.java

/** * Txt文件格式导出具体类 * @author [email protected] * */publicclass TxtFileExport extends FileExportAbstraction {    @Override    publicvoidexportFile() {        String readContent = fileSouce.readContent();        ",将内容导出为.txt格式");    }}

8. < role: Expand abstract Class > Xmlfileexport.java

/** * xml文件格式导出具体类 * @author  [email protected] * */publicclass XmlFileExport extends FileExportAbstraction {    @Override    publicvoidexportFile() {        String readContent = fileSouce.readContent();        ",将内容导出为.xml格式");    }}

9. < role: Expand abstract Class > Pdffileexport.java

/** * pdf文件格式导出具体类 * @author  [email protected] * */publicclass PdfFileExport extends FileExportAbstraction {    @Override    publicvoidexportFile() {        String readContent = fileSouce.readContent();        ",将内容导出为.pdf格式");    }}

10. Client Test class: Client.java

 Public classClient { Public Static void Main(string[] args) {Fileexportimpl fileoracle =NewFileexportfromoracle (); Fileexportimpl Filemysql =NewFileexportfrommysql (); Fileexportimpl Filesqlserver =NewFileexportfromsqlserver (); Fileexportabstraction Filetxtexport =NewTxtfileexport (); Fileexportabstraction Filexmlexport =NewXmlfileexport (); Fileexportabstraction Filepdfexport =NewPdffileexport ();//If we want to export data in XML format from OracleFilexmlexport.setfilesource (fileoracle);        Filexmlexport.exportfile (); System. out. println ("--------------------\ n");//If we are exporting data in TXT format from OracleFiletxtexport.setfilesource (fileoracle);        Filetxtexport.exportfile (); System. out. println ("--------------------\ n");//If we want to export the data in PDF format from MySQLFilepdfexport.setfilesource (Filemysql);    Filepdfexport.exportfile (); }}

11. The result of implementation is as follows:

已成功连接到Oracle数据库已成功从Oracle数据库中读取到了内容,将内容导出为.xml格式--------------------已成功连接到Oracle数据库已成功从Oracle数据库中读取到了内容,将内容导出为.txt格式--------------------已成功连接到MySql数据库已成功从MySql数据库中读取到了内容,将内容导出为.pdf格式

12. Follow-up system expansion
①, now if demand for new add a file input format such as: HTML format
Then just write a new subclass of the Fileexportabstraction abstract class to output the HTML format, without having to modify any other classes and code that doesn't need to modify another dimension.
②, now if requirements require a new class of database types such as: Sybase
You only need to write a new implementation class for the Fileexportimpl interface, get the content from the Sybase database, modify the Jdbcdrivermanager.java class, add connections and access to the Sybase database.

This shows that in the two changing dimensions of any extension of a dimension, there is no need to modify the original system, improve the scalability and maintainability of the system.

Vi. Other
Key Benefits:
(1) Separating the abstract interface and its implementation part. Bridging mode uses the association between objects to decouple the inherent binding between abstractions and implementations so that abstractions and implementations can evolve along their respective dimensions. The so-called abstractions and implementations evolve along their respective dimensions, meaning that abstractions and implementations are no longer in the same inheritance hierarchy, but rather "subclass" them, so that they each have their own subclasses so that any combination of subclasses can obtain multi-dimensional composite objects.
(2) In many cases, bridging mode can replace the multi-layer inheritance scheme, multi-layer succession scheme violates the "single responsibility Principle", the reusability is poor, and the number of classes is very many, bridging mode is a better solution than multi-layer inheritance scheme, it greatly reduces the number of subclasses.
(3) bridge mode to improve the scalability of the system, in the two changing dimensions of any extension of a dimension, do not need to modify the original system, in line with the "open and close principle."

Bridge pattern in Java design mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.