This is the 28th day of my participation in the August Text Challenge.More challenges in August

Decorators are still widely used today. When the coffee beans are fresh from the coffee machine, espresso is nothing, watered down with water is American, a cappuccino with milk, and a latte with more milk. The coffee bean is always black and bitter water, we add different things to become different products, this is the decorator pattern. Adding a layer of packaging can transform you into something different, but the essence remains the same.

What are the benefits of decorators? It may not be a benefit, but in some cases it’s a solution. For example, some SDK code or classes that are marked as final cannot be modified, but are not satisfied with their simple functionality, you can use decorators to extend their functionality without writing too much code. Or in a common scenario where a class has too many lines and is complex enough, but new requirements force you to do something new, decorators can be used to do this. Because the decorator class and the original class is a delegate relationship, is a weak relationship. The class diagram is as follows:

Decorators are used extensively in the JDK, such as:


Reader reader = new FileReader("file.log");

Reader reader = new BufferedReader(new FileReader("file.log"));
Copy the code

The following class diagram shows that the two readers are essentially the same thing, so they can be extended directly and easily:

If you look at this, you see that the adapter patterns are very similar to those mentioned before, but they actually have a common name: wrapper patterns. They’re both wrapping a class to do more, but the difference is:

  • The purpose of the adapter pattern is to transform one interface into another, and its purpose is to reuse the interface by changing it.
  • The decorator pattern does not change the interface of the decorator object, but rather preserves the original interface but enhances the functionality of the original object, or changes the processing of the original object to improve performance

No matter how decorated the decorator is, it and the decorated class have the same behavior, but more functionality.