AD

Design Patterns Decorator - decorator

Decorative patterns, The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Dynamically to an object to add some additional responsibilities. Is to add features, Decorator pattern is more flexible than subclassing.

Let us understand this sentence.

Design of our system of "door" to the class. <!--[ If! Vml ]--><!--[ endif] ->

Now, a place in the system need a alarm Door, how do you come to it? You may write a subclass of Door AlarmDoor, add a sub-class in which the unique method of alarm (). Ah, that use the alarm gates in place you have to let customers (users) using a warning that the door, or can not use this unique method. Moreover, this also **s the Liskov Substitution Principle.

Perhaps you say, then this method to Door inside, so do not unified? But this all doors must have alarm, at least a "dumb" alert. When your system is only one or two places in the alarm gate, which is obviously unreasonable - although you can use the default adapter to make up for it.

At this time, you may consider using decorative pattern to the door to add some extra dynamic features.

Let us look at the composition of decorative patterns, do not rush to solve the above problems, to the following natural to understand!



Component
The original class interface
ConcreteComponent
Function implementation class. The specific implementation class Component
Decorator
Decorative abstract class. As with ConcreteComponent Component interfaces are inherited, but the way to achieve ConcreteComponent different. ConcreteComponent inherited by a simple way to implement; and Decorator Component object is encapsulated by the Committee with the action so that ways.
The following is a typical code for Decorator:
Listing 1
public class Decorator implement Component {
Component component;

public Decorator (Component component) {
this**ponent = component;
}

public void doSomething () {
...
this**ponent.doSomething ();
...
}
}
ConcreteDecoratorA and ConcreteDecoratorB
Decorative concrete. The specific implementation class Decorator

Here is the class diagram

Design Patterns Decorator - decorator


The following look at a more concrete example:

Central Perk's name as "Friends" and world-renowned, and their stores are almost all over the world. They develop so fast, so they are eager to achieve a set of time management, automated billing by the computer system.

For a coffee shop, it changes all those points? Variety of condiments and price change? Coffee varieties and price change? The combination of coffee and spices change? YES! For a coffee shop, it often happens in these areas will certainly change! So, when these changes occur, our billing system to do? If the spices change, then we can re-adjust the level from code Beverage base class, which is too bad; if the coffee is changed, we can add or delete a sub-class can be, this seems to be tolerable; then coffee and Changes in the way the combination of spices it? If a customer ordered a cup of black coffee and a chocolate sugar plus two, or customer ordered a cup of decaffeinated coffee (Decaf) plus three condensed milk and a sugar it?

So back to the Decorator Pattern, with the same pattern described earlier, is also decorated by a very simple model, in particular, draw the class diagram and sequence diagram, everything is clear. There is only one place in need of special stress: Decorator Decorator mode is a very special class, both inherited from Component] [IS A relations, but also maintain a reference point Component instance] [HAS A relationship, another point of view , Decorator with the Component between the dynamic combination of both relations have static inheritance, WHY? here, so why should the design? We said above, the combination has the advantage of the object at run time to increase duties, Decorator] [HAS A Component is intended to ConcreteDecorator dynamically at run time to ConcreteComponent increased responsibilities that are relatively well understood; then Decorator inherited from Component What is the purpose? Here, the purpose of inheritance is only one thing can be unified, and was decorated by a decorator's interface, from another angle, whether it is ConcretComponent or ConcreteDecorator, they are Component, user code can be unified as a Component to handle them, This brings the benefits of a deeper level is that the object of a decorator who decorated the function of the object code for user expansion functions are completely transparent, because the user code references are Component, so I will not be trimmed the object being decorated, the reference to an error code to its users, in fact, has no effect, because decoration around the user code references types of objects are Component, this is really too perfect! Decorator pattern decorative reunification through inheritance and was decorated by the interfaces, obtained through a combination of dynamic expansion in the run-time object is the ability of a decorator.

We give another example of life, the saying goes, "clothes horse in the saddle", the words which those patterns with a decorative look Context Translation, "who decorated by beautiful clothes, the men become handsome, women become beautiful;. " Corresponding to the above class diagram, where one corresponds to the ConcreteComponent, and beautiful clothes, corresponds to ConcreteDecorator; another point of view, and nice clothes HAS A] [together, with the handsome or beautiful, but they were [IS A ], but also a man to do things, but may be more attractive to the opposite sex (extension)!

Decorative patterns from the perspective of those who consider the issue, the relationship between coffee and condiments should be: Coffee is decorated object is decorated by condiments, coffee and spices can be combined, but no matter how you mix, coffee or coffee! So it's that simple ah!

Specific look at the following class diagram:

Design Patterns Decorator - decorator


As shown, Beverage or beverage base class of all, it corresponds to the Decorator pattern class diagram in the Component, all the decorative object is the base class; HouseBlend, DarkRoast, Espresso, Decaf is a specific drink (coffee) species, corresponding to the front of the ConcreteComponent, that is, the specific object being decorated; CondimentDecorator corresponds to the front of the Decorator, who is decorated with an abstract class; and Milk, Mocha, Soy, Whip the spices are specific for the previous ConcreteDecorator, but also is the specific decorator. Let us further through specific understanding of what the code Decorator pattern based accounting system implementation.

Beverage is the base class for all the drinks, which corresponds to the decorator pattern class diagram in the Component, all the base class for objects to be decorated


package zieckey.designpatterns.study.decorator;

/**
*
* The Decorator design pattern-decorative pattern
*
* Beverage Is the base class for all beverages, it corresponds to the decoration to model a class diagram. Component
*
* @author zieckey
*
*/
public abstract class Beverage {

public String getDescription()
{
return "Unknown Beverage";
}

public abstract double cost();
}




HouseBlend, DarkRoast, Espresso, Decaf is a specific drink (coffee) types, corresponding to the front of the ConcreteComponent, which is a specific object to be decorated;


package zieckey.designpatterns.study.decorator;

/**
* DarkRoast Coffee, specific Component
* @author zieckey
*
*/
public class DarkRoast extends Beverage {

@Override
public double cost() {
// TODO Auto-generated method stub

return 0.88;
}

public String getDescription() {
return "DarkRoast";
}
}





package zieckey.designpatterns.study.decorator;

/**
* Expresso Coffee, specific Component
* @author zieckey
*
*/
public class Expresso extends Beverage {

@Override
public double cost() {
// TODO Auto-generated method stub

return 0.95;
}

public String getDescription() {
return "Expresso";
}

}




CondimentDecorator corresponds to the front of the Decorator, is an abstract class Decorator


package zieckey.designpatterns.study.decorator;

/**
* Decorative abstract class
* @author zieckey
*
*/
public abstract class CondimentDecorator extends Beverage{
Beverage beverage;

public CondimentDecorator( Beverage beverage )
{
this.beverage = beverage;
}

public double cost()
{
return beverage.cost();
}

}




The Milk, Mocha, Soy, Whip the spices are specific for the previous ConcreteDecorator, who is the decorative concrete


package zieckey.designpatterns.study.decorator;

//mocha Coffee, specific Decorator

public class MochaDecorator extends CondimentDecorator {
public MochaDecorator(Beverage beverage) {
super(beverage);
}

public String getDescription() {
return beverage.getDescription() + "+Mocha";
}

public double cost() {
return 0.20 + beverage.cost();
}
}





package zieckey.designpatterns.study.decorator;

/**
* soy Coffee, specific Decorator
* @author zieckey
*
*/
public class SoyDecorator extends CondimentDecorator {

public SoyDecorator(Beverage beverage) {
super(beverage);
}

public String getDescription() {
return beverage.getDescription() + "+Soy";
}

public double cost() {
return 0.15 + beverage.cost();
}
}




Okay. Test code given below:


package zieckey.designpatterns.study.decorator;

public class ClientTest {

/**
* @param args
*/
public static void main(String[] args) {
Beverage expresso = new Expresso();
CondimentDecorator soyDecorator1 = new SoyDecorator( expresso );
CondimentDecorator mochaDecorator1 = new MochaDecorator( soyDecorator1 );

System.out.println( mochaDecorator1.getDescription() + ", costs, " + mochaDecorator1.cost() );

Beverage darkRoast = new DarkRoast();
CondimentDecorator soyDecorator2 = new SoyDecorator( darkRoast );
CondimentDecorator mochaDecorator2 = new MochaDecorator( soyDecorator2 );
System.out.println( mochaDecorator2.getDescription() + ", costs, " + mochaDecorator2.cost() );

}

}




Output:


Expresso+Soy+Mocha, costs, 1.2999999999999998
DarkRoast+Soy+Mocha, costs, 1.23




At this point should make it clear what is decorative pattern of the bar.

Description:
This article is the following three connections Notes to sort by, and I believe a look at three Bowen will have a greater harvest.

Reference:

**blog.csdn**/ai92/archive/2005/03/01/307046.aspx

****cnblogs**/justinw/archive/2007/06/11/779356.html

****lifevv**/sysdesign/doc/20071116210104656.html
标签: lt, implementation class, class interface, abstract class, design patterns, subclass, vml, composition, component object, component component, decorative patterns, doors, endif, decorator pattern, class component, gates, decorators, dynamic features, liskov substitution principle, component interfaces
分类: Java
时间: 2010-11-25

相关文章

  1. Design Patterns - Decorator pattern

    1, the concept description The model to the client transparently extend object functionality. The decorator pa ...
  2. Design patterns and reusable object-oriented software

    Seen before in the forum a good blog about design patterns. The most progress also strike while the iron is ho ...
  3. Design Patterns as seen (decorator decorator)

    Header: (from Design Patterns) To extend the code base, usually give it to add a new class or new methods. Som ...
  4. Design Patterns - Decorator 1 (turn)

    Decorative patterns (Decorator) Scene 1 issue 1.1 Calculation of the complex bonus Consider a practical applic ...
  5. Design Patterns - Decorator 3 (transfer)

    3 model to explain 3.1 understanding of decorative patterns (1) mode function Decorative patterns can be dynam ...
  6. Design Patterns - Decorator 2 (transfer)

    2 Solutions 2.1 Decoration model to solve To solve the above problems, a reasonable solution is to use decorat ...
  7. Design Patterns - Decorator 4 (switch)

    In each module itself? Take a well-known for the three-tier structure, but also to consider from top to bottom ...
  8. Design Patterns of Reading Notes Decorator (Decorator)

    Decorator Decorator pattern is to create a new class for a certain class of dynamic add new features or enhanc ...
  9. Notes Head First Design Patterns

    Author: water tree reprint URL: http://mifunny.info/ Head First Design Patterns first lesson: strategy models ...
  10. JUnit framework for design and use of design patterns

    JUnit framework for design and use of design patterns Translation: Yong-Jun Hu hu.yong.jun @ ctgpc.com.cn be a ...
  11. Design patterns Daquan

    Bitter about the recent study of several open-source framework for source code, to be interested in design mod ...
  12. Design patterns notes - structured

    Adapter (Adapter) The interface of a class into another interface clients expect. Adapter pattern makes the or ...
  13. design patterns java study notes

    Today take some time to learn the system under design mode, from the Internet to find a point of information a ...
  14. Design Patterns Essay Series: opening - model and principles of the [transfer]

    Transfer from Justin http://www.cnblogs.com/justinw/archive/2006/11/28/574573.html Opening - patterns and prin ...
  15. From the database connection associated with the five kinds of design patterns

    Recently looking at design patterns such information. Sudden inspiration, from the database connection to the ...
  16. JSF framework using design patterns introduced

    Design patterns can help users abstract the details at a higher level, a better understanding of architecture. ...
  17. MM from the chase about 23 kinds of Design Patterns Java

    MM from the recovery of 23 species on Java design patterns 1, FACTORY-chase MM missed, please eat, McDonald's ...
  18. Utilize design patterns

    The article discusses the following issues: 1, 2, design patterns metaphor, why use design patterns 3, 4, when ...
  19. 23 kinds of design patterns interesting insights

    23 kinds of interesting insights design patterns Posts by Li Yang editor at 2010-3-17 08:57 1, FACTORY-chase M ...