Java and mode 26-14th-Bridge Mode

Source: Internet
Author: User
Tags abstract definition
Document directory
  • Source code

The bridge mode is the object structure mode. It is also known as the handle and body mode or interface mode. The purpose of the bridge mode is to "decouple abstract actions and implementation so that the two can change independently ".

Intention of the Bridge Model

  Although the bridge mode is not a frequently used mode, it is helpful to understand the object-oriented design principles, including the "open-closed" principle and the combination/aggregation Reuse Principle. Understanding these two principles helps to form correct design ideas and cultivate a good design style.

The purpose of the bridge mode is to "decouple abstract actions and implementation so that the two can change independently ". This sentence is short, but for the first time, people who read this sentence may think for a long time and cannot understand what they mean.

This sentence has three keywords: abstraction, implementation, and decoupling. Understanding the concepts represented by these three words is the key to understanding the intention of the bridge model.

  • Abstraction

Extracting common and essential features from numerous things and discarding non-essential features is abstract. For example, apple, bananas, raw pears, peaches, and so on. They share the same characteristics as fruits. The process of getting the fruit concept is an abstract process. To be abstract, you must compare them. If there is no comparison, you cannot find a common part. Common features are the features that distinguish a class of things from other things. These differentiated features are also called essential features. Therefore, the common feature of extracting things is to extract essential features of things and discard non-essential features. Therefore, abstraction is also a process of cropping. In the process of abstraction, the same and different parameters depend on the abstract. The abstract angle depends on the purpose of analyzing the problem.

Normally, if a group of objects have the same features, they can be described through a common class. If some classes have the same features, they can often be described through a common abstract class.

  •   Implementation

The specific implementation given in abstraction is implementation.

An instance of a class is the instantiation of this class. A specific subclass is the instantiation of its abstract superclass.

  •   Decoupling

Coupling is a strong association between two entities. Removing their strong associations is the relief of coupling, or decoupling. Here, decoupling means to free up coupling between abstraction and reality, or change strong associations between them into weak associations.

The so-called strong association is the association that has been determined during the compilation period and cannot be dynamically changed during the runtime; the so-called weak Association, is the association that can be dynamically determined and can be dynamically changed during the running period. Obviously, in Java, the inheritance relationship is strongly correlated, while the aggregation relationship is weak Association.

Change the inheritance relationship between two roles to an aggregation relationship, that is, change the strong association between them to a weak Association. Therefore, the so-called decoupling in the bridge mode refers to the use of aggregation rather than inheritance between the abstraction and implementation of a software system, so that the two can change relatively independently. This is the purpose of the bridge model.

Structure of the Bridge Mode

As shown in the following figure, the schematic structure of a schematic system that implements the bridge mode is as follows:

We can see that this system has two levels:

IAbstract level structure composed of abstract roles and modified abstract roles.

  2. Implementation level structure composed of implementation roles and two specific implementation roles.

  The following roles are involved in the Bridge Mode:

Abstract action role:Abstract The definition and save a reference to the implemented object.

Modify the abstract role:Extends abstract roles, and modifies the abstract definition of the parent class.

Implementor role:This role provides an interface to implement the role, but does not provide a specific implementation. It must be noted that this interface is not necessarily the same as the interface definition of abstract roles. In fact, these two interfaces can be very different. An implemented role should only provide underlying operations, while an abstract role should only provide operations at a higher level based on underlying operations.

Concreteimplementor role:This role provides the specific implementation of the role interface.

 

Abstract roles are like the handles of a cup, while realization roles and specific implementation roles are like cups of cups. The handle controls the cup body, which is the source of the "handle body" alias in this mode.

Objects encapsulate behaviors, and actions are implemented by methods. In this schematic system, classes in the abstract hierarchical structure encapsulate the operation () method, while classes in the implementation hierarchical structure encapsulate the operationimpl () method. Of course, there are usually more than one method in the actual system.

Methods In the abstract hierarchical structure can delegate their own functions to the corresponding implemented object, which means that the abstract role can delegate to different implemented objects, to dynamically convert your functions.

Source code

Abstract corner class, which declares a method operation () and provides its implementation. This implementation is implemented by delegating the implemented object (calling the operationimpl () method.

Public abstract class extends action {protected implementor impl; Public extends action (implementor impl) {This. impl = impl;} // example method public void operation () {impl. operationimpl ();}}

 

Modify abstract roles

Public class refinedmenaction extends action {public refinedabstraction (implementor impl) {super (impl) ;}// other operation methods public void otheroperation (){}}

Implementation roles

Public abstract class implementor {/*** example method to implement some specific functions required by the abstract Part */public abstract void operationimpl ();}

Specific implementation roles

Public class concreteimplementora extends implementor {@ override public void operationimpl () {// specific operation }}

 

Public class concreteimplementorb extends implementor {@ override public void operationimpl () {// specific operation }}

 

Generally, each method in an implemented role should have a method corresponding to one of the abstract roles, but the opposite is not necessarily true. In other words, the abstract role interface is wider than the implemented role interface. Abstract roles not only provide methods related to the implemented roles, but also provide other methods. The implemented roles are often used only to implement the behaviors related to the abstract roles.

 

 

Use Cases

Consider the actual business function of sending a prompt message. Basically, all systems with business process processing have such functions. For example, if there is an unfinished file on the OA, you need to send a message to remind him.

From the business perspective, messages are divided into common messages, urgent messages, and urgent messages. Different types of messages have different service functions. For example, a urgent message is added to a message, in addition to adding urgent messages, a reminder record will be made, and the reminder will be continued in the short time; from the aspect of message sending means, there are also system short messages, mobile phone Short Messages, emails, and so on.

Use the Bridge Mode to solve the problem

According to the functional requirements of the business, business changes have two dimensions. One Dimension is abstract messages, including common messages, urgent messages, and urgent messages, these abstract messages have a certain relationship, and the urgent messages and urgent messages expand the common messages. The other dimension is the specific message sending method, including short messages, emails, and short messages in the system. These methods are equal and can be switched.

The root cause of the problem is that the abstract and implementation of messages are mixed, which leads to a change in one latitude, which will lead to a change in the other latitude, this makes program expansion very difficult.

To solve this problem, we must separate the two latitudes, that is, separating the abstract and implementation parts so that they are independent of each other. In this way, we can implement independent changes and make expansion easier. The abstract part is the function corresponding to each message type, and the Implementation part is the various message sending methods. Define the interfaces for the abstract part and the implementation part according to the structure of the bridge mode, and then implement them separately.

Source code

Abstract message class

Package COM. bankht. bridge. bridgemessage;/*** @ Author: Special Forces-AK47 * @ Creation Time: 05:26:06, December 26, ** @ Class description: abstract message class */public abstract class abstractmessage {// The object messageimplementor impl holding an implementation part;/*** constructor, input the object ** @ Param impl * for implementation */Public abstractmessage (messageimplementor impl) {This. impl = impl;}/*** send a message, delegate to the implementation method ** @ Param message * content of the message to be sent * @ Param touser * receiver of the Message */Public void sendmessage (string message, string touser) {This. impl. send (message, touser );}}

 

Common Message class

Package COM. bankht. bridge. bridgemessage;/*** @ Author: Special Forces-AK47 * @ Creation Time: 05:27:22, December 26, ** @ Class description: common Message class */public class commonmessage extends abstractmessage {public commonmessage (messageimplementor impl) {super (impl) ;}@ overridepublic void sendmessage (string message, string touser) {// for common messages, directly call the parent class method and send the message to super. sendmessage (message, touser );}}

 

Urgent message

Package COM. bankht. bridge. bridgemessage;/*** @ Author: Special Forces-AK47 * @ Creation Time: 05:27:43, December 26, ** @ Class description: urgent message class */public class urgencymessage extends abstractmessage {public urgencymessage (messageimplementor impl) {super (impl);} @ overridepublic void sendmessage (string message, string touser) {message = "urgent:" + message; super. sendmessage (message, touser);}/*** extends its new functions, monitor the processing status of a message ** @ Param messageid * The number of the monitored message * @ return the processing status of the monitored message */public object Watch (string messageid) {// obtain the status of a message based on the Message ID, organize it into a monitored data object, and return NULL ;}}

 

Unified interface for sending messages

Package COM. bankht. bridge. bridgemessage;/*** @ Author: Special Forces-AK47 * @ Creation Time: 05:28:04, December 26, ** @ Class description: unified interface for sending messages */public interface messageimplementor {/*** send a message ** @ Param message * content of the message to be sent * @ Param touser * receiver of the Message */Public void send (string message, string touser );}

Implementation of short messages in the system

Package COM. bankht. bridge. bridgemessage;/*** @ Author: Special Forces-AK47 * @ Creation Time: 05:28:25, December 26, ** @ Class description: implementation class */public class messagesms implements messageimplementor {@ overridepublic void send (string message, string touser) {system. out. println ("use the short message method in the system to send the message '" + message + "' to" + touser );}}

 

Implementation of Short Message

Package COM. bankht. bridge. bridgemessage;/*** @ Author: Special Forces-AK47 * @ Creation Time: 05:28:44, December 26, ** @ Class description: short Message Implementation class */public class messageemail implements messageimplementor {@ overridepublic void send (string message, string touser) {system. out. println ("Send message '" + message + "' to" + touser) using the short message method );}}

 

Client type

Package COM. bankht. bridge. bridgemessage;/*** @ Author: Special Forces-AK47 * @ Creation Time: 05:29:05, December 26, ** @ Class description: client class */public class client {public static void main (string [] ARGs) {// create a specific implementation object messageimplementor impl = new messagesms (); // create a common message object abstractmessage message = new commonmessage (impl); message. sendmessage ("overtime application quick batch", "Li Zong"); // switch the implementation method to an email and send impl = new messageemail () again (); // create an urgent message object message = new urgencymessage (impl); message. sendmessage ("overtime application quick approval", "Li Zong ");}}

 

Observe the above example and you will find that the abstract part and the implementation part are separated and can be changed independently of each other without affecting each other. Therefore, adding a new message processing (Urgent message) in the abstract Part does not affect the implementation of message sending. In turn, the method for sending messages (Short Messages on mobile phones) is added ), message Processing is not affected.

Advantages of the Bridge Mode

Separating abstraction and implementation

The Bridge Mode separates the abstract part and the implementation part, thus greatly providing system flexibility. Separate the abstract Part and implementation part and define interfaces separately, which helps to layer the system and generate a better structured system.

 

Better scalability

  The bridge mode allows the abstract part and the implementation part to expand independently without affecting each other, thus greatly improving the scalability of the system.

 

 

Use of Bridge Mode in Java

A typical example of the Bridge Mode in Java applications is the JDBC driver. JDBC provides a common interface for all relational databases. An application system dynamically selects an appropriate drive and sends commands to the database engine through the drive. This process delegates the abstract role behavior to the role.

The abstract role can issue query commands for any database engine, because the abstract role does not directly deal with the database engine, and the JDBC driver is responsible for the underlying work. Because of the existence of JDBC drivers, the application system can evolve independently without relying on the details of the database engine. At the same time, the database engine can also evolve independently from the details of the application system. Shows the two independent hierarchical structures. The left side is the jdbc api hierarchical structure, and the right side is the JDBC driver hierarchical structure. Applications are built on JDBC APIs.

As a hierarchical structure, the application system is relatively independent from the JDBC driver, and there is no static strong association between them. The application system interacts with the JDBC driver through delegation. This is an example of a bridge mode.

The architecture of JDBC separates the abstract part from the specific part, so that the abstract part and the specific part can be expanded independently. For an application, you only need to select different drivers to allow the program to operate on different databases without changing the application, so as to port the program to different databases. For the driver, implementing different drivers for databases does not affect applications.

 

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.