Decorative mode of grinding design mode-2

Source: Internet
Author: User
ArticleDirectory
    • 2.1 decoration mode to solve
    • 2.2 schema structure and description
    • 2.3 decoration mode sample code
    • 2.4 example of rewriting using decoration Mode
2 solution 2.1 Solution

A reasonable solution for solving the above problems is to use the decoration mode. So what is the decoration mode?
(1) Definition of decorative patterns


(2) How to Use the decoration mode to solve the problem
Although simplified, the business is much simpler, but there are no fewer problems to solve, we still need to solve: to transparently add features to an object and implement dynamic combinations of features.
The so-called transparent addition of a function to an object, in other words, is to add a function to an object, but this object cannot be known, that is, it cannot be modified. The realization of the ability to add a function to the transparency of an object can naturally achieve a dynamic combination of functions, for example, the original object has a function, and now transparent to it to add a B function, is it equivalent to dynamically combining a and B functions.
To add a function to an object transparently, that is, to extend the object's function, some people have proposed a scheme to use inheritance, but soon the program was rejected, what about reducing or modifying functions? In fact, inheritance is a very inflexible method of reuse. So we can use "Object combination" and some people have come up with a new solution. This solution has been approved by everyone.
In the implementation of the decoration mode, to seamlessly integrate with the code that originally used the decorated object, an abstract class is defined to implement the same interface as the decorated object, then, in the specific implementation class, the converted objects are decorated, and new functions are added before and after the transition, which enables adding functions to the decorated objects, this idea is very similar to "Object combination. If you are not familiar with object combinations, see section 3.1 in section 2nd.
During the transfer, if you feel that the function of the decorated object is no longer needed, you can replace it directly, that is, it is not a transfer, but a completely new implementation in the decoration object.

2.2 schema structure and description

The structure 1 of the decoration mode is shown below:

 

 

Figure 1 decorative pattern structure
Component:
The interface of the component object, which can dynamically add responsibilities to these objects.
Concretecomponent:
A specific component object that implements the component object interface is usually the original object decorated by the decorator, that is, you can add responsibilities to this object.
Decorator:
The abstract parent class of all decorators needs to define an interface consistent with the component interface and hold a component object, which is actually holding a decorated object.
Note that the decorated object is not necessarily the most primitive object, or it may be the object after being decorated by other decorators. It is the same interface implemented in any case, that is, the same type.
Concretedecorator:
The actual modifier object to implement the function to be added to the decoration object.

2.3 decoration mode example Code

(1) Let's take a look at the Interface Definition of the component object. The sample code is as follows:

 
/*** Interface of the component object, which can dynamically add responsibilities to these objects */public abstract class component {/*** Sample Method */public abstract void operation ();}

(2) If the interface is defined, let's look at the implementation object of the specific component. The sample code is as follows:

 
/*** Specific object implementing the component object interface */public class concretecomponent extends component {public void operation () {// corresponding function processing }}

(3) let's take a look at the abstract modifier object. The sample code is as follows:

 
/*** The modifier interface maintains an interface object pointing to the component object, define an interface */public abstract class decorator extends component {/*** holding the component object */protected component;/*** constructor that is consistent with the component interface, input component object * @ Param component object */Public decorator (Component component) {This. component = component;} public void operation () {// forward the request to the component object. You can execute some additional actions before and after forwarding component. operation ();}}

(4) let's take a look at the specific modifier implementation object. Here there are two sample objects, one indicating the adding status and the other indicating the Adding responsibilities. Let's take a look at the demo object with the added status. The sample code is as follows:

/*** Specific implementation object of the decorator, add responsibility to the component object */public class concretedecoratora extends decorator {public concretedecoratora (Component component) {super (component );} /*** added status */private string addedstate; Public String getaddedstate () {return addedstate;} public void setaddedstate (string addedstate) {This. addedstate = addedstate;} public void operation () {// call the method of the parent class, you can execute some additional actions before and after the call // when processing here, you can use the added super. operation ();}}

Next let's take a look at the demo object for Adding responsibilities. The sample code is as follows:

 

 
/*** Specific implementation object of the decorator, add responsibility to the component object */public class concretedecoratorb extends decorator {public concretedecoratorb (Component component) {super (component );} /*** responsibilities to be added */private void addedbehavior () {// implementation of duties to be added} public void operation () {// call the method of the parent class, you can execute some additional actions before and after calling super. operation (); addedbehavior ();}}

 

 

2.4 example of rewriting using decoration Mode

After reading the basic knowledge of the decoration mode, we should consider how to use the decoration mode to rewrite the previous example. To use the decoration mode to rewrite the previous example, the following changes will be taken:

    • First, you need to define an interface for the component object, which defines the Business Method for Calculating the bonus, because the external interface is used to operate the objects in the object structure composed of the decoration mode.
    • You need to add a basic object that implements the component interface so that it can return a reward of 0.
    • To treat each calculation bonus rule as a modifier object, you need to define a uniform abstract modifier object for them to constrain the interface of each specific modifier.
    • Implement the rules for calculating bonuses into specific decorator objects

First, let's take a look at the overall structure of the current example to better understand and grasp the example, as shown in Figure 2:

 

 

Figure 2 overwrite the program structure of the example in decoration Mode
(1) component interfaces and basic implementation objects for bonus Calculation
In the Component Interface for calculating the bonus, you need to define the original business method, that is, the method for calculating the bonus. The sample code is as follows:

/*** Component Interface for calculating the bonus */public abstract class component {/*** calculates the bonus of a person in a certain period of time. Some parameters are not used in the demo, * However, it is used in actual business implementation to indicate that this is a specific business method, * therefore, these parameters are reserved. * @ Param User: the person who calculated the bonus * @ Param begin calculates the bonus start time * @ Param end calculates the bonus end time * @ return someone else in a certain prize in a certain period of time */public abstract double calcprize (string user, date begin, date end );}

Provides a basic implementation for this business interface. The sample code is as follows:

 
/*** The basic class used to calculate the bonus. It is also the object decorated by the decorator */public class concretecomponent extends component {public double calcprize (string user, date begin, date end) {// It is only a default implementation, and no return 0;} by default ;}}

(2) define an abstract decorator
Before defining the decorator, define the common parent classes of each decorator. Here, define the methods to be implemented for all the decorator objects. This parent class should implement the component interface to ensure that the decorated object can still be decorated. The sample code is as follows:

/*** Interface of the decorator, the same interface must be implemented with the decorated object */public abstract class decorator extends component {/*** holding the decorated component object */protected component C; /*** pass in the decorated object through the constructor * @ Param C the decorated object */Public decorator (component C) {This. C = C;} public double calcprize (string user, date begin, date end) {// return C. calcprize (user, begin, end );}}

(3) define a series of decorator objects
A specific modifier object is used to calculate a bonus rule. Now there are three rules for calculating the bonus, so we should implement three decorators, let's look at their implementations in turn.
These decorators involve the same tempdb as before, so we will not go into details here.
First, let's look at the decorator that calculates the business bonus for the current month. The sample code is as follows:

/*** Decorator object, calculate the current month's Business Bonus */public class monthprizedecorator extends decorator {public monthprizedecorator (component C) {super (c);} public double calcprize (string user, date begin, date end) {// 1: first obtain the previously calculated bonus double money = super. calcprize (user, begin, end); // 2: Calculate the business bonus for the current month, obtain the business amount for the current month by personnel and time, and then multiply the value by 3% double prize = tempdb. mapmonthsalemoney. get (User) * 0.03; system. out. println (User + "current month Business Bonus" + Prize); return money + Prize ;}}

Next, let's look at the decorator that calculates the accumulated bonus. The sample code is as follows:

 
/*** Decorator object, calculates the cumulative bonus */public class sumprizedecorator extends decorator {public sumprizedecorator (component C) {super (c);} public double calcprize (string user, date begin, date end) {// 1: first obtain the previously calculated bonus double money = super. calcprize (user, begin, end); // 2: Calculate the accumulated bonus. In fact, you should obtain the accumulated business amount by personnel, and then multiply it by 0.1% // for a simple demonstration, assume that your accumulated business amount is 1000000 yuan double prize = 1000000*0.001; system. out. println (User + "accumulative bonus" + Prize); return money + Prize ;}}

Next, let's look at the decorator that computes the team's business bonus for the current month. The sample code is as follows:

 
/*** Decorator object: Calculate the team's business bonus for the current month */public class groupprizedecorator extends decorator {public groupprizedecorator (component C) {super (c );} public double calcprize (string user, date begin, date end) {// 1: first obtain the previously calculated bonus double money = super. calcprize (user, begin, end); // 2: Calculate the Business Bonus of the team for the current month, and calculate the total business amount of the team, then multiply by 1% // assume that all of them are double group = 0.0; For (double D: tempdb. mapmonthsalemoney. values () {group + = D ;}double prize = Group * 0.01; system. out. println (User + "current month team Business Bonus" + Prize); return money + Prize ;}}

(4) decorator client
to use the decorator client, you must first create the decorated object, then, create the desired decoration object. Next, combine the decoration object and then decorate the previous object in sequence.
there are many similar examples, such as the decoration in life, for example, decorating the walls: the original brick walls are not decorated, which is like the objects to be decorated, first, you need to brush the putty and flatten the wall. This is better than the original brick wall for decoration, and the putty for the paint is like a decoration device object, next, we should paint the wall. This is like a decoration. The wall paint is like another decoration object, and the decorated object is not the original brick wall, instead, it is the wall that is decorated by the putty modifier. That is to say, the wall that is behind the ornament is based on the decoration of the front ornament and continues to be decorated. It is similar to a layer-by-layer stacked function.
In the same way, the calculation bonus is also the same. First, the bonus object is created, and then the type of bonus to be calculated is combined and calculated in sequence. The final result is the total bonus. The sample code is as follows:

/*** Use the client in decorative mode */public class client {public static void main (string [] ARGs) {// create a class to calculate the basic bonus first, this is also the decoration object component C1 = new concretecomponent (); // then, decorate the basic computing bonus. here you need to combine various decorations // description, it is recommended that there be no sequential restrictions between each ornament, // that is, decorator and decorator should be the same. // decorator d1 = new monthprizedecorator (C1) is calculated based on the bonus of the common business personnel ); decorator D2 = new sumprizedecorator (D1); // Note: you only need to use the final combination of objects to call the business method and call them back in sequence. // Date objects are not used, therefore, if null is passed, double Zs = d2.calcprize ("Zhang San", null, null); system. out. println ("=========== Zhang San deserves a bonus:" + ZS); double ls = d2.calcprize ("Li Si", null, null); system. out. println ("=========== Li Si deserves a bonus:" + ls); // if it is a business manager, you also need a computing team's bonus calculation: decorator D3 = new groupprizedecorator (D2); double WW = d3.calcprize ("Wang Wu", null, null); system. out. println ("=========== Manager Wang deserves a bonus:" + ww );}}

Test it and check the result. The example is as follows:

 
Michael Jacob's business bonus for the current month is 300.0 Michael Jacob's cumulative bonus is 1000.0 ========== Michael Jacob deserves the bonus: 1300.0 Li Si's business bonus for the current month is 600.0 Li Si's accumulated bonus of 1000.0 ========== Li Si deserves the bonus: 1600.0 Wang Wu's business bonus for the current month: 900.0 Wang Wu's accumulated bonus: 1000.0 Wang Wu's team's business bonus for the current month: 600.0

During the test, the corresponding decorator is called sequentially to execute business functions according to the combination sequence of the decorator. This is a recursive call method, take the "Wang Wu" bonus calculation of the business manager as an example. Draw a picture to illustrate the bonus calculation process and see how to call it, as shown in 3:


Figure 3 combination and call process of decoration mode examples
This figure shows the combination and calling process of the decoration mode.

 

As in the preceding example, the calculation logic of the basic bonus calculation object is too complex and requires different operations under different circumstances. For flexibility, you can distribute a variety of bonus calculation methods to different decorative objects and use dynamic combinations to add the bonus calculation function to basic bonus calculation objects, each decorator is equivalent to a part of the calculation bonus.
This method is obviously more flexible than adding subclass to the basic calculation bonus object, because the origin of the decoration mode is to use the object combination method, and then add some functions in the combination. In order to achieve a layer-by-layer Assembly effect, the decoration mode also requires that the decoration device implement the same business interface as the decorated object so that it can be combined in the same way in sequence.
Flexibility is also reflected in the dynamics. If it is inherited, all the class instances have this function, and the decoration mode can dynamically add features for several object instances, instead of adding functions to the entire class. For example, in the above example, during the client test, Michael Jacob only combined two functions and Wang Wu combined three functions, but the original calculation bonus classes were the same, it just dynamically adds different functions for it.

 

 

To be continued

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.