Decorative mode of grinding design mode-4

Source: Internet
Author: User
ArticleDirectory
    • 3.3 decoration mode and AOP
    • 3.4 Advantages and Disadvantages of decoration Mode
    • 3.5 think about the decoration Mode
    • 3.6 related models
3.3 decoration mode and AOP

The decoration mode and AOP have similarities in their thoughts. Some may not know much about AOP. The following describes the basic knowledge of AOP.
1: What is AOP-Aspect-Oriented Programming
AOP is a programming paradigm that provides a different perspectiveProgramStructure to improve Object-Oriented Programming (OOP ).
In object-oriented development, the system perspective is usually vertical. For example, we often draw the following system architecture diagram, which is from top to bottom by default. The upper layer depends on the lower layer, as shown in Figure 5:

Figure 5 system architecture Diagram
What about each module? Taking the layer-3 architecture that everyone is familiar with, it is also taken into consideration from the top down, usually the presentation layer calls the logic layer, and the logic layer calls the data layer, as shown in Figure 6:


Figure 6 three-tier architecture

slowly, more and more people have found that there are some common functions in each module, such as log management and transaction management, as shown in Figure 7:
figure 7 common functions

At this time, when thinking about these common features, we are thinking about the problem horizontally, which is different from the general object-oriented Vertical thinking. Obviously, we need a new solution, at this time, AOP stands out.
AOP provides a mechanism for developers to describe the cross-concern, and can automatically route the cross-concern to the object-oriented software system, thus realizing the modularization of the Cross-concern.
AOP can encapsulate the logic or responsibilities that are unrelated to the business but called by the business module, such as transaction processing, log management, and permission control, to reduce system duplication.CodeTo reduce the coupling between modules and facilitate future operability and maintainability.
The reason why AOP is powerful is that it can automatically weave the functional modules of the Cross-concern into the software system. What does this mean?
First, let's take a look at the absence of AOP. In a conventional object-oriented system, how to deal with such common functions is to extract these functions and then call them wherever necessary, just draw the public module that calls General logs. If it is similar to other modules, do not draw them, as shown in Figure 8:


Figure 8 call Public Functions

It is clear that the application module actively calls the public module, that is, the application module must be clear about the functions of the public module, and there are still specific call methods, the application module depends on the public module and is coupled. As a result, it is very difficult to modify the public module.
Let's see what happens with AOP and draw a picture to illustrate it, as shown in Figure 9:


Figure 9 AOP call

At first glance, there is no difference with no AOP above. Is it true? Take a closer look. There is a very, very big change, that isAll arrows are reversed.In the past, the application system took the initiative to call various public modules, and now it has become the public modules that are actively woven back to the application system.
Do not underestimate this change, so that the application system does not need to know the public function module, that is, the application system and the public function are decoupled. Public functions will be woven from the outside into the application system as appropriate. We will not discuss who will implement such functions and how to implement them, we pay more attention to this idea.
If the above process is compared according to the decoration mode, the business function objects can be seen as the objects to be decorated, and each public module is like a decoration device, you can add functions to business function objects transparently.
So from one side, the decoration mode is similar to the function to be implemented by AOP, except that the implementation methods of AOP are different, and they are more flexible and configurable.A more important change of AOP is the ideological change-"master-slave transposition ",It turns the previously called function modules into passive waiting, and even many new functions are woven without knowing it.

2: Use the decoration mode to make effects similar to AOP
The following example shows how to use the decoration mode to add some common functions, such as permission control, logging, and transparent functions back to the business function module to achieve similar effects of AOP.
(1) first define the business interface
This interface is equivalent to the component in decorative mode. Note that the interface is used here, rather than the abstract class, although the abstract class is used to define components as the standard implementation of the decoration mode, however, if you do not need to provide public functions for sub-classes, you can implement interfaces. This should be explained first, so that some friends may think that this is not a decoration mode, the sample code is as follows:

 
/*** Product sales management business interface */public interface goodssaleebi {/*** saves the sales information. Originally, there should be multiple sales data records, which is too troublesome. for demonstration purposes, simply click * @ Param user operator * @ Param customer * @ Param salemodel sales data * @ return whether the data is successfully saved */Public Boolean sale (string user, string customer, salemodel );}

Define the objects that encapsulate business data. The sample code is as follows:

/*** Encapsulate the data of the sales order, and briefly express some */public class salemodel {/*** sold items */private string goods; /*** sales quantity */private int salenum; Public String getgoods () {return goods;} public void setgoods (string goods) {This. goods = goods;} public int getsalenum () {return salenum;} public void setsalenum (INT salenum) {This. salenum = salenum;} Public String tostring () {return "product name =" + goods + ", quantity bought =" + salenum ;}}

(2) define basic business implementation objects. The sample code is as follows:

 
Public class goodssaleebo implements goodssaleebi {public Boolean sale (string user, string customer, salemodel) {system. out. println (User + "saves" + customer + "purchase" + salemodel + "sales data"); Return true ;}}

 

(3) Next we should implement the public functions. To implement these public functions as a decoration device, we need to define an abstract parent class for them. The example is as follows:

/*** Interface of the decorator, the interface */public abstract class decorator implements goodssaleebi {/*** needs to implement the same interface as the decorated object */protected goodssaleebi EBI; /*** pass in the decorated object through the constructor * @ Param EBI the decorated object */Public decorator (goodssaleebi EBI) {This. EBI = EBI ;}}

(4) decorator for permission Control
First, check whether you have the operation permission. If you have the permission, continue calling. If you do not have the permission, do not call it recursively. Instead, output the prompt that you do not have the permission. The sample code is as follows:

 
/*** Implement permission control */public class checkdecorator extends decorator {public checkdecorator (goodssaleebi EBI) {super (EBI);} public Boolean sale (string user, string customer, salemodel) {// simple, only let Michael perform this function if (! "James ". equals (User) {system. out. println ("sorry" + User + ", you do not have the permission to save the sales order"); // you will no longer call the function of the decorated object return false;} else {return this. ebi. sale (user, customer, salemodel );}}}

(5) The decorator for logging is to record logs after the function is executed. The sample code is as follows:

/*** Implement logging */public class logdecorator extends decorator {public logdecorator (goodssaleebi EBI) {super (EBI);} public Boolean sale (string user, string customer, salemodel) {// executes the business function Boolean F = This. ebi. sale (user, customer, salemodel); // after the business function is executed, record the log dateformat df = new simpledateformat ("yyyy-mm-dd hh: mm: ss sss "); system. out. println ("log record:" + User + "on" + DF. format (new date () + "saves a sales record. The customer is" + customer + "and the purchase record is" + salemodel); Return F ;}}
 
(6) Use these decorator in combination
In combination, permission control should be executed first. Therefore, the decorator of log record will first call the original business object to combine it on the outermost surface, therefore, the decorator of the log record is combined in the middle.
As mentioned above, it is recommended that there be no sequential restrictions between the decorator, but in actual application, it should be based on specific functional requirements. When necessary, there can also be sequential restrictions, however, we should try to avoid this situation.
The client test code is as follows:
Public class client {public static void main (string [] ARGs) {// get the business interface, composite decorator goodssaleebi EBI = new checkdecorator (New logdecorator (New goodssaleebo ())); // prepare the test data salemodel = new salemodel (); salemodel. setgoods ("Moto mobile"); salemodel. setsalenum (2); // call the business function Ebi. sale ("Zhang San", "Zhang Sanfeng", salemodel); Ebi. sale ("Li Si", "Zhang Sanfeng", salemodel );}}

 

The running result is as follows:

 

Let's take a good look at it. Isn't it even disturbing the original business object and It's woven into a new function? That is to say, without the knowledge of the original business, a new function is added to the original Business Objects transparently, thus simulating the implementation of the AOP function.
In fact, this method can be applied to project development. In the future, it will add data check, permission control, logging, and other functions to the project's business objects, you do not need to process these functions on Business Objects. Business Objects can focus more on specific business processing.

3.4 Advantages and Disadvantages of decoration Mode
    • More flexible than inheritance
      From the perspective of adding functions to objects, the decoration mode is more flexible than inheritance. Inheritance is static, and all child classes have the same function. However, the decoration mode separates functions into each decorator, and dynamically combines functions at runtime by means of object combination. What functions does each decorated object ultimately have, it is determined by the dynamic combination of functions during the runtime.
    • Easier function Reuse
      The decoration mode disperses a series of complex functions into each decorator. Generally, a decorator only implements one function, which makes it easy to implement the decorator, more importantly, this is conducive to the reuse of the decoration device function. You can add multiple identical decoration devices to an object, or use a decoration device to decorate different objects, in this way, the function of the decorator is reused.
    • Simplified high-level Definition
      The decoration mode can add any number of functions to the object by combining the decorator. Therefore, you do not need to define all the functions in the upper-level definition, instead, you can define the most basic functions. when you need them, you can combine the corresponding decorators to complete the required functions.
    • Will produce a lot of fine-grained objects
      As mentioned above, the decoration mode is to distribute a series of complex functions into each decoration device. Generally, a decoration device only implements one function, which produces many fine-grained objects, the more complex the function is, the more fine-grained objects are required.

 

3.5 think about the decoration Mode

1: essence of the decoration Model
The essence of the decoration mode:Dynamic combination.
Dynamic is the means, and combination is the purpose. The combination here has two meanings: one is the combination of dynamic functions, that is, the combination of dynamic decorators; the other is the combination of objects, by combining objects, you can add transparent functions to the decorated objects.
However, it should be noted that the decoration mode can not only add functions, but also control function access and completely implement new functions, you can also control whether the decoration function runs before or after the decoration function.
In short, the decoration mode is a mode that simplifies and disperses complex functions and dynamically combines them as needed during operation.

2: When to choose the decoration Mode
We recommend that you use the decoration mode in the following situations:

    • If you want to add roles to an object dynamically and transparently without affecting other objects, you can use the decoration mode, which is almost the main function of the decoration mode.
    • If child classes are not suitable for extension, you can consider using the decoration mode, because the decoration mode uses the "Object combination" method. This method is not suitable for subclass extension. For example, the extension function requires too many subclasses, resulting in explosive growth in the number of subclasses.

 

3.6 related models
  • Decoration mode and adapter Mode
    There are two unrelated models. Put them together because they have a common alias: wrapper.
    The two modes have different functions. The adapter mode is used to change the interface, while the decoration mode is used to change the object function.
  • Decoration mode and Combination Mode
    The similarities between the two models involve recursive calls to objects. From a certain point of view, decoration can be seen as a combination of only one component.
    However, they have different purposes. The decoration mode is to dynamically add functions to objects, while the combination mode is to manage the combination objects and leaf objects, provide them with a consistent operation interface to the client for ease of use.
  • Decoration mode and Policy Mode
    These two modes can be used in combination.
    The policy mode can also realize the function of dynamically changing objects, but the policy mode is only a selection layer, that is, selecting a specific implementation Class Based on the policy. The decoration mode is not a layer, but a recursive call, and countless layers can be called. As long as the object combination of the decoration device is combined, it can be called in turn, so the decoration mode will be more flexible.
    In addition, the Policy mode changes the functions of the original object. Unlike the decoration mode, the latter is the object that passes through the decoration of the previous decoration device, that is, the rule mode changes the kernel of the object, while the decoration mode changes the shell of the object.
    These two modes can be used in combination. You can use the policy mode in a specific decoration device to select a more specific implementation method. For example, another problem with the previous bonus calculation is that the base number involved in the calculation is different, and the calculation method of the bonus is also different. For example, assume that Zhang San and Li Si participate in the calculation of the same bonus. The total sales amount of Zhang San is 20 thousand yuan, while that of Li Si is 80 thousand yuan. Their calculation formulas are different, assume that the calculation rule of the bonus is that the sales volume is less than 50 thousand, with a uniform value of 3%, while that of more than 50 thousand is 50 thousand, that of the excess is 4%.
    Participating in the calculation of the same bonus means that the same ornament can be used, but the calculation formula is different under different conditions within the ornament. How can we choose a specific implementation strategy? You can use the policy mode, that is, the combination of the decoration mode and the policy mode.
  • Decoration mode and template method mode
    This is a mode with similar features.
    The template method mode is mainly used inAlgorithmIf the skeleton is fixed, if the algorithm steps are not fixed, that is, a relatively dynamic algorithm step, you can use the decoration mode, because when using the decoration mode, the Assembly of the decorator is actually equivalent to the assembly of a call algorithm step, which is equivalent to a dynamic algorithm skeleton.
    Since the decoration mode can be used to assemble and call dynamic algorithm steps, the algorithm steps are fixed, that is, the functions implemented by the template method mode, therefore, the decoration mode can simulate the template method mode function.
    However, please note that only functions can be simulated. The design objectives, original functions, and essential ideas of the two models are different.
     

 

 The decoration mode is over. Thank you for watching. 

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.