Decorator

xiaoxiao2021-03-06  50

definition

Name: Decortator Structure: Intent: Dynamically add some additional responsibilities to an object. In terms of increased function, Decorator mode is more flexible compared to generated subclasses. Applicability: Add responsibility to a single object in a dynamic, transparent manner without affecting other objects. Handling those responsibilities that can withdraw. When the method of generating subclasses cannot be expanded. One case is that there may be a large number of independent extensions, to support each combination, which will generate a large number of subclasses, resulting in explosive growth. Another situation may be because class definitions are hidden, or class definitions cannot be used to generate a subclass. effect:

Classic Case

1. Java.IO In IO processing, Java abstracts the data as a stream. In the IO library, the most basic is two objects that have both processed and entered separately (for the sake of narrative, this only involving byte streams, character streams, but is provided in InputStream and OutputStream. The simplest flow processing method, only read / write characters, no buffer processing, no file, and so on. They just provide the purest abstraction, the simplest function.

How to add functions to handle more complicated things? You may think of inheritance. Yes, inheritance does solve the problem, but inheritance also brings a bigger problem, it requires a subclass for each function. For example, I first implemented three subclasses, which are used to process files, buffers, and read / write data, but if I need a class that can handle files and buffer features? At this time, you must inherit, rewrite the code. In fact, only the combination of these three functions is already a big number. If you add other features, the combined IO library, if you only use inheritance, I am afraid you really want to be It is getting crazy.

Decorator mode can solve this problem. Decorator literally means decoration, on the original basis, you can add a function. This is the intention of Decorator. For example, for the above problem, only three Decorator classes are required, representing three functions of file processing, buffer, and data, on this basis, can be completed by adding decoration, without having to be complicated Subcretence inherited. More importantly, the comparison relay mechanism says that Decorator is dynamic, can be added or removed at runtime, and thus has greater flexibility than inheritance mechanisms.

MyStringBuffer = New StringBuffer ("This Is A Sample String to Be Read"); FilterInputStream MyStream = New LinenumberInputStream (New BufferInputStream

NEW STRINGBUFFERINPUTSTREAM (MyStringBuffer)); MyStream.Read (); MyStream.Line ();

Best Practices

1,

Related mode

1,

Reference article

1,

转载请注明原文地址:https://www.9cbs.com/read-79634.html

New Post(0)