Decorator mode for Java design patterns

Source: Internet
Author: User

Directory

  

First, the problem introduced
Ii. Principles of Design
Third, use the decorator mode to solve the problem
Four, the characteristics of the decorator model
V. Definition of decorator pattern
Vi. the implementation of the decorator pattern
Seven, java.io in the package of decorator mode

First, the problem introduced

Coffee Shop Class Design:

A beverage base class, a variety of beverage classes inherit this base class and calculate their price.

To add a variety of spices in the beverage, consider adding some Boolean variables to the base class to indicate whether to add a variety of spices, the cost of the base class () to calculate the price of the various spices, the sub-category cover costs (), and in which the cost of the Super-class (), plus the price of a particular beverage, to calculate the price

Disadvantages: The number of classes explosion, the new function of the base class addition does not apply to all subclasses, seasoning price changes, the emergence of new spices will require changes to existing code, and some sub-categories are not suitable for certain spices and other situations ...

Ii. Principles of Design

Classes should be open to extensions and closed for modifications.

Our goal is to allow classes to be easily extended and to match new behavior without modifying existing code.

What are the benefits of achieving such a goal? This design is resilient to change and can accept new features to respond to changing needs.

It is not easy to have an OO design that is both open and closed, and it is generally not necessary to design every part of the design.

Following the open-close principle, it is common to introduce new levels of abstraction and increase the complexity of the code.

We need to focus on where the design is most likely to change, and then apply the open-close principle.

Third, use the decorator mode to solve the problem

Ways to solve a coffee shop drink problem:

Take the beverage as the main body, then "decorate" the beverage with seasoning at run time.

For example, customers want Mocha (Mocha) and milk foam (Whip) deep-roasted coffee (darkroast):

Darkroast inherits from Beverage and has a cost () method.

The first step is to start with the Darkroast object;

In the second step, the customer wants Mocha, so create a Mocha decorator object and use it to wrap the Darkroast object (wrap) up;

In the third step, the customer wants the milk bubble, so build a whip object and use it to wrap the Mocha object, (Mocha and whip also inherit from beverage, there is a cost () method);

Finally, for the customer to calculate money, by calling the most outer ring decorator (Whip) cost () can be. The cost of Whip () will first be entrusted to the object it decorates (Mocha) to calculate the price, and then add the price of the milk bubble. Mocha's cost () is similar.

Four, the characteristics of the decorator model

Decorators and decorated objects have the same super-type .

You can wrap an object with one or more adorners.

Because the decorator and the decorator have the same type, any occasion where the original object is needed can be replaced with a decorated object.

  The decorator may, before and/or after the act entrusted to the decorator, add his or her own behavior to achieve a specific purpose.

Objects can be decorated at any time, so you can decorate objects dynamically and without limits at run time with your favorite decorators.

V. Definition of decorator pattern

The decorator mode dynamically attaches responsibility to the object. To extend functionality, decorators provide a more resilient alternative than inheritance.

Vi. the implementation of the decorator pattern

The implementation class diagram is as follows:

Decorators and decorators have a common superclass, using inheritance to achieve " type matching ", rather than using inheritance to obtain "behavior"; combine decorators and decorators to add new behavior.

Detailed Source code:

 PackageCom.blankjor.decorator;/*** @desc Abstract Beverage Class (abstract component) *@authorblankjor * @date May 14, 2017 morning 11:14:06*/ Public Abstract classBeverage {String description= "Unkown Beverage";  PublicString getdescription () {returndescription; }    /*** Abstract Price calculation method * *@return     */     Public Abstract DoubleCost ();} PackageCom.blankjor.decorator;/*** @desc concentrated beverage (specific components) *@authorblankjor * @date May 14, 2017 morning 11:20:11*/ Public classEspressoextendsBeverage { PublicEspresso () {Description= "Espresso"; } @Override Public DoubleCost () {return1.99; }} PackageCom.blankjor.decorator;/*** @desc House Blend Drinks (Specific components) *@authorblankjor * @date May 14, 2017 morning 11:20:11*/ Public classHouseblendextendsBeverage { PublicHouseblend () {Description= "House Blend"; } @Override Public DoubleCost () {return.20; }} PackageCom.blankjor.decorator;/*** @desc Abstract Decorator class *@authorblankjor * @date May 14, 2017 morning 11:17:12*/ Public Abstract classCondimentdecoratorextendsBeverage {/*** You can get a description of your own seasoning for all the spices in the back.*/     Public AbstractString getdescription ();} PackageCom.blankjor.decorator;/*** @desc Mocha Seasoning (concrete decorator) *@authorblankjor * @date May 14, 2017 morning 11:23:36*/ Public classMochaextendscondimentdecorator {beverage beverage;  PublicMocha (beverage beverage) { This. Beverage =Beverage; } @Override PublicString getdescription () {returnBeverage.getdescription () + ", Mocha"; } @Override Public DoubleCost () {return.20 +Beverage.cost (); }} PackageCom.blankjor.decorator;/*** @desc Soy seasoning (concrete decorator) *@authorblankjor * @date May 14, 2017 morning 11:20:11*/ Public classSoyextendscondimentdecorator {beverage beverage;  PublicSoy (beverage beverage) { This. Beverage =Beverage; } @Override PublicString getdescription () {returnBeverage.getdescription () + ", Soy"; } @Override Public DoubleCost () {return.60 +Beverage.cost (); }} PackageCom.blankjor.decorator;/*** @desc Whip Seasoning (concrete decorator) *@authorblankjor * @date May 14, 2017 morning 11:20:11*/ Public classWhipextendscondimentdecorator {beverage beverage;  PublicWhip (beverage beverage) { This. Beverage =Beverage; } @Override PublicString getdescription () {returnBeverage.getdescription () + ", Whip"; } @Override Public DoubleCost () {return.40 +Beverage.cost (); }} PackageCom.blankjor.decorator;/*** @desc Test Decorator mode *@authorblankjor * @date May 14, 2017 morning 11:29:50*/ Public classMaintest { Public Static voidMain (string[] args) {//Create a seasoningBeverage Beverage =NewEspresso (); //Description and PriceSystem.out.println (beverage.getdescription () + "$" +beverage.cost ()); Beverage Beverage1=NewHouseblend (); Beverage1=NewMocha (BEVERAGE1); Beverage1=NewWhip (BEVERAGE1); Beverage1=NewSoy (BEVERAGE1); System.out.println (Beverage1.getdescription ()+ " $" +beverage1.cost ()); Beverage Beverage2=NewEspresso (); Beverage2=NewMocha (Beverage2); Beverage2=NewWhip (Beverage2); Beverage2=NewSoy (Beverage2); Beverage2=NewMocha (Beverage2); System.out.println (Beverage2.getdescription ()+ " $" +beverage2.cost ()); }}

Operation Result:

Decorators and decorators have a common superclass, using inheritance to achieve " type matching ", rather than using inheritance to obtain "behavior"; combine decorators and decorators to add new behavior.

To solve the specific problem of the beverage in this article, the figure component is beverage (can be abstract class or interface), and concretecomponent for a variety of drinks, Decorator (abstract decorator) as a condiment abstract class or interface, Concretedecoratorx is a variety of specific spices.

Because of the combination of objects, it is possible to mix and match the beverage and seasoning more flexibly.

Code External details:

When implemented in code, the decorator can be passed into the decorator by the constructor, as in the final invocation form as follows:

Beverage beverage = new Darkroast ();

Beverage = new Mocha (beverage);

Beverage = new Whip (beverage);

The two-tier wrapper is completed, and the cost () function of the beverage is then called to get the total price.

Seven, java.io in the package of decorator mode

The disadvantage of decorator mode: Adding a large number of small classes in the design, if overused, can complicate the program.

Reference: http://www.cnblogs.com/mengdd/archive/2013/01/03/2843439.html

Decorator mode for Java design patterns

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.