Design pattern—(3) Decorator pattern

tags: Design Patterns  Decorator

1. Mode definition

Dynamically attach responsibilities to objects. In terms of extending functions, decorators provide a more flexible alternative than inheritance. (The principle of openness and closedness is maintained: open for expansion and closed for modification)

Combining decorators and specific components is adding new behaviors. Composition and delegation can dynamically add new behaviors at runtime. Although inheritance is also one of the extended forms, it is inflexible design and relies on inheritance. The behavior of the class can only be determined statically at compile time.

Problem Description

Design different types of beverages, beverages can be added with ingredients, such as milk can be added, and support for dynamic addition of new ingredients. Every time an ingredient is added, the price of the beverage will increase, requiring calculation of the price of a beverage.

The picture below shows the addition of Mocha ingredients to the DarkRoast drink, followed by Whip ingredients. DarkRoast is wrapped in Mocha, and Mocha is wrapped in Whip. They all inherit from the same parent class and both have a cost() method. The cost() method of the outer class calls the cost() method of the inner class.

Two, pattern class diagram


 ConcreteComponent and abstract decorator (Decorator) both inherit from abstract component (Component), concrete decorator (ConcereteDecoratorA and ConcereteDecoratorB) inherit from abstract decorator.

 The method implementation of a concrete component does not need to depend on other objects, and the decorator combines a component so that it can decorate other decorators or concrete components. The so-called decoration is to put the decorator on the decorator (specific component), thereby dynamically expanding the function of the decorator. Part of the decorator's method is its own, which belongs to its function, and then calls the decorate's method to achieve it, thus retaining the decorate's function. As you can see, the specific component should be the lowest level of the decoration level, because only the method implementation of the specific component does not need to depend on other objects.

Third, the solution class diagram of specific problems 


beverage: beverage
DarkRoast: The first choice of coffee house blend for deep culture coffee

Code

//Component interface (can also abstract component class)
public interface Beverage {
    public double cost();
}
//Specific component class HouseBlend 
public class HouseBlend implements Beverage{
    @Override
    public double cost() {
        return 1;
    }
}
//Specific component class DarkRoast 
public class DarkRoast implements Beverage{
    @Override
    public double cost() {
        return 1;
    }
}
//Abstract decorator class implements component interface
public abstract class CondimentDecorator implements Beverage{
    protected Beverage beverage;//That is 1
}
//Specific decorator class Mocha 
public class Mocha extends CondimentDecorator {

/*How to enable a Mocha to reference a Beverage?
 1. Use an instance variable beverage to record the beverage beverage, which is the decorated person
 2. Think of a way to let the decorated person (beverage Beverage) be recorded in the instance variable. The method: use the beverage as a parameter of the constructor, and then the constructor records the beverage in the instance variable.
*/

    public Mocha(Beverage beverage) {
        this.beverage = beverage;//That is 2
    }

    @Override
    public double cost() {
        return 1 + beverage.cost();//beverage.cost() delegation method
    }
     /*To calculate the price of the Mocha drink, first delegate the call to the decorated object,
                 Calculate the price and then add the price of Mocha to get the final result. */
}
//Specific decorator class Milk 
public class Milk extends CondimentDecorator {

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

    @Override
    public double cost() {
        return 1 + beverage.cost();
    }
}


//Main function implementation
public class StartbuzzCoffee {
    public static void main(String[] args) {
        Beverage beverage = new HouseBlend();
        beverage = new Mocha(beverage);
        beverage = new Milk(beverage);
        System.out.println(beverage.cost());
    }
}
 Output

3.0

Four, the decorator pattern in Java I/O


InputStrean Abstract component

FileInputStream (byte read),
StringBufferInputStream,
ByteArrayInputStream
The above three areSpecific components

FilterInputStream Is anAbstract decorator

The following class that inherits FilterInputStream isSpecific decorator
For example:
LineNumberInputStream: Calculate the number of lines
BufferedInputStream: Buffered input to improve performance, and its readLine() method to read a line of text input data.

Five, design principles

Classes should be open for extension and closed for modification (open and closed principle): that is, no code modification is required when adding new features.
In the question in this chapter, the principle is embodied in the beverage can dynamically add new ingredients without modifying the beverage code. The observer model also conforms to this principle. It is impossible for all class designs to satisfy this principle, and the principle should be applied where changes are most likely to occur.

Intelligent Recommendation

Design Pattern Learning (3) Decorator Pattern

Design principle: The class should be open for extension and closed for modification Our goal is to allow classes to be easily extended, and new behaviors can be matched without modifying the code. If...

Java design pattern 3: decorator pattern

1. Decorator mode 1. Introduction: The decorator pattern dynamically attaches responsibility to the object. To extend the functionality, decorators provide a more flexible alternative than inheritance...

Decorator mode of design pattern (3)

Welcome everyone's continued attention. Last time, we combined the class diagram derived from the first article, and the second article based on the class diagram to write the actual code, which has a...

C ++ design pattern-3.decorator decorator

Decorator Decorator, I think it is a very clever design pattern, he can use the so-called "decoration chain" to expand an existing object without modifying the original code  ...

Design Pattern-Decorator Pattern / Decorator Pattern (Decorator)

definition People who need to refactor the project must master the decorator mode It refers to attaching functions to the object without changing the original object, providingMore flexible than inher...

More Recommendation

Design pattern decorator pattern

Decorator modeMainly used to dynamically add some additional responsibilities to an object. In terms of adding functionality, the decorator mode is more flexible than generating subclasses. In general...

Design Pattern - Decorator Pattern

What is the decorator mode? Dynamically add some extra functionality to an object, and colleagues don't change the structure of the object. Decorator pattern elements Decorated object (Bread) Decorati...

Design pattern----decorator pattern

SchoolReport.java code is as follows: The code for FouthGradeSchoolReport.java is as follows: The Decorator.java code is as follows: The HighScoreDecorator.java code is as follows: The SortDecorator.j...

Design Mode entry - template method pattern

background: We want to implement the program brew: The brewing process: 1) boiling water 2) 3 with boiling water and soaking tea) tea into a cup 4) and lemon; Process for making coffee: 1) boiling wat...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top