Decorator pattern of Java design pattern

Decorator mode:
Dynamically adds some extra properties or behavior to the object. The decorator mode is more flexible than using inheritance.

UML diagram:

587163-697df51451031108.png
Decorator.png

In general, the decorator mode has the following participants:

  • Component: The parent class of the decorator and the decorator. It is an interface or abstract class that defines the basic behavior.
  • ConcreteComponent: defines the specific object, that is, the decorator
  • Decorator: An abstract decorator that inherits from Component and extends ConcreteComponent from an outer class. For ConcreteComponent, you don't need to know the existence of the Decorator, which is an interface or abstract class.
  • ConcreteDecorator: a concrete decorator used to extend ConcreteComponent

Note: The decorator and the decorator object have the same supertype, because the decorator and the decorator must be of the same type.Inheritance is used here to achieve type matching, rather than using inheritance to get behavior.

Using inheritance design subclasses can only be statically determined at compile time, and all subclasses inherit the same behavior; using a combination of methods to extend an object can be dynamically extended at runtime. Decorator mode follows the open-close principle:Classes should be open to extensions and closed to modifications.With decorators, we can implement new decorators to add new behavior without modifying existing code, and if we rely solely on inheritance, we must modify the existing code whenever new behavior is required.

Example:

Suppose a dessert shop sells cakes. In addition to cakes, you can also arrange fruits, candles, etc. on the cake, but fruits and candles are available at an extra charge.Suppose the price of a cake is 66 yuan, and the fruit and candle need to pay an extra 10 yuan respectively. How do you calculate the price dynamically?The code posted in the example has been uploaded to Github:Decorator mode.
First, define the component class, which is also the superclass of the decorator and the decorator Sweet .java:

public abstract class Sweet {
    String description = "Sweet";

    public String getDescription() {
        return description;
    }

    public abstract double cost();
}

Define the decorator cake class, Cake .java:

public class Cake extends Sweet {
    @Override
    public String getDescription() {
                 Return "a cake";
    }

    @Override
    public double cost() {
        return 66;
    }
}

Define the abstract decorator class Decorator.java:

public abstract class Decorator extends Sweet {
    public abstract String getDescription();
}

Define the specific decorator fruit class, FruitDecorator.java:

public class FruitDecorator extends Decorator {
    Sweet sweet;

    public FruitDecorator(Sweet sweet) {
        this.sweet = sweet;
    }

    @Override
    public String getDescription() {
                 Return sweet.getDescription() + ",fruit";
    }

    @Override
    public double cost() {
        return sweet.cost() + 10;
    }
}

Define the specific decorator candle class, CandleDecorator.java:

public class CandleDecorator extends Decorator {
    Sweet sweet;

    public CandleDecorator(Sweet sweet) {
        this.sweet = sweet;
    }

    @Override
    public String getDescription() {
                 Return sweet.getDescription() + ", candle";
    }

    @Override
    public double cost() {
        return sweet.cost() + 10;
    }
}

Finally settle the price according to different options:

public static void main(String[] args) {

    Cake cake = new Cake();
         System.out.println(cake.getDescription() + "total cost" + cake.cost());

    FruitDecorator fruitDecorator = new FruitDecorator(cake);
         System.out.println(fruitDecorator.getDescription() + "total cost" + fruitDecorator.cost());

    CandleDecorator candleDecorator = new CandleDecorator(fruitDecorator);
         System.out.println(candleDecorator.getDescription() + "total cost" + candleDecorator.cost());

    }

The full code address has been uploaded to Github:Decorator mode.
Execution result:

a cake, a total cost of 66.0
 A cake, fruit, a total cost of 76.0
 A cake, fruit, a candle, costing a total of 86.0

visible,The decorator pattern can be very flexible and dynamically add new behavior to the decorator. Its shortcomings also show that more objects must be managed, but the decorator pattern can be modeled like a factory pattern or a generator. Use one piece to avoid this problem.

PS: When we use the java.IO class, we are similar to the following:

new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream( "io.txt" )));

The java.IO class also uses the decorator mode! Is it clear a lot?

to sum up:
1. The decorator and the decorator object have the same supertype, so in any occasion where the original object (decorator) is needed, the decorated object can be used instead of the original object.
2, can wrap an object (decorator) with one or more decorators
3、The decorator can add his or her own behavior before or after the entrusted decorator's behavior to achieve a specific purpose.
4, the decorator can be decorated at any time, so you can decorate the object with your favorite decorator dynamically and indefinitely at runtime.
5, the decorator will lead to a lot of small objects, if used excessively, it will make the program complicated.

Intelligent Recommendation

Java Design Pattern --------Decorator Pattern

Note: The content of this blog is from the Head First design mode, and only organizes and summarizes the articles. 1. The problem leads to We need to make a new order system for a coffee shop. The pre...

Java design pattern (decorator pattern)

1. The UML class diagram is as follows 2、Decorator.java 3、Person.java 4、AbstractDecorator.java 5、ShoesDecorator.java 6、TShirtDecorator.java 7. Use operation result: Wore a pair of shoes wore a T-Shirt...

Java design pattern----------decorator pattern

1 Introduction The decorator pattern is a structural design pattern. The purpose of using this mode is to expand the class more flexibly without affecting the structure of the original class. Some stu...

java-design pattern-decorator pattern

The key design of the decorator pattern is the component interface, and then both decorators and specific roles implement this interface. Next, use the decorator mode to realize the situation where th...

Design pattern java【decorator pattern】

What is the decorator mode? Dynamically attach responsibilities to the object. If you want to extend the functionality, decorators provide a more flexible alternative than inheritance When to use deco...

More Recommendation

Classification task 8 (fanwai)-parameter setting

Put the parameters I used in this part...

Springboot Excel View (POI)

Springboot Excel View (POI)   application:Export data using the view, save it to the Excel file Description:You can download data directly to the Excel file directly.     **************...

andriod simple installation of XposedInstaller

XposedInstaller andriod version 5.0 or less andriod version 5.0 or higher, you can go to the official website to download 1. sdk correspondence between 6.0 Android 5.0(Lollipop )——SDK21 An...

[CDH] Sqoop version of Hadoop, Hive and Sqoop pseudo-distributed environment to build

1, CDH version of pseudo-distributed Hadoop environment to build (1) Since the / opt is the owner of the root, become root, new directory cdh-5.3.6 in / opt:opt]# mkdir cdh-5.3.6 Change cdh-5.3.6 and ...

Create app links for instant apps (App Link 4)

AndroidThe instant app is a small version of your app that runs without an installation. Users simply click on the URL to launch your app without having to install it.APK. Therefore, all instant appli...

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

Top