Design Patterns -- Decorator Patterns

Why use the decorator pattern?

For example, we need a cup of milk tea now, and then we want to add pearls and coconut fruit to the milk tea.

However, if you directly modify the category of milk tea, it does not meet the principle of modifying the original category as little as possible.

So we need a way to add new properties to the original class without modifying the original class.

What is the decorator pattern?

Definition : To dynamically attach responsibilities to objects, to extend functionality, decorators provide a more flexible alternative to inheritance.

Decorator pattern is to dynamically extend the functionality of an object without having to change the original class file and use inheritance. It wraps the real object by creating a wrapper object, which is a decoration.

Design Principle : Classes should be open for extension and closed for modification.

Implement :

The decorator and the decorated must be of the same type, that is, there must be a common parent class. Because the adorner and the adorned are of the same type, the adorner can replace the adorned, so that the adorned has the unique behavior of the adorner. According to the idea of ​​the decorator pattern, we can implement new decorators to add new behaviors at any time. If you use inheritance, you need to modify the original program whenever you need to add new behavior.

Problem solved :

We can make milk tea and CondimentDecorator have a common parent class Beverage, and then derive subclasses of pearl, coconut and other condiments from CondimentDecorator.

If we want to add pearls, we can directly use milk tea (or milk tea with some attributes added) as an attribute of the pearl instance, that is, there must be an attribute pointing to the parent class Beverage in Decorateor.

It is also because milk tea and condiments use the same parent class, so the condiment instance can directly replace the milk tea instance.

Applications such as: layer-by-layer packaging of input and output streams

java.io.BufferedReader;
java.io.FileReader;
java.io.Reader;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325865207&siteId=291194637