Java Decorator Mode
In Java, many classes in the I/O package are the embodiment of the typical modifier mode, such:
NewBufferedOutputStream (OutputStream out)
NewBufferedInputStream (InputStream in );
NewPrintWriter (OutputStream out)
NewFilterReader (Reader in );
The decoration class implements the same interface as the decorated class,
The decoration class does not care which implementation class is used to decorate it,
In the same business method, the decoration class calls the decoration class method to enhance the decoration class function.
Example:
public interface IReader {void read();}
public class Reader implements IReader {@Overridepublic void read() {System.out.println("read of Reader");}}
public class BufferedReader implements IReader {private IReader mReader;public BufferedReader(IReader reader) {this.mReader = reader;}@Overridepublic void read() {System.out.println("read of BufferedReader");mReader.read();}}
/** Features: * (1) the decoration object has the same interface as the real object. In this way, the client object can interact with the decoration object in the same way as the real object. (2) A decoration object contains a reference of a real object (3) the decoration object accepts all requests from the client. It forwards these requests to real objects. (4) Decoration objects can add some additional functions before or after forwarding these requests. In this way, you can add additional functions externally without modifying the structure of the given object during running. In the object-oriented design, the function of a given class is extended by inheritance. After the decoration, they hold real objects to enhance their functions. The difference between the modifier and the adapter mode about the new responsibilities: the adapter can also add new responsibilities during the conversion, but the main purpose is not here. The decorator mode adds new responsibilities to the decorator. About the object of the package: the adapter knows the details of the adapter (that is, the adapter class ). The decorator only knows what its interface is. The specific type (whether it is a base class or another derived class) is only known during running. */Public class Test {public static void main (String [] args) {Reader reader = new Reader (); reader. read (); System. out. println ("----------"); BufferedReader bufferedReader = new BufferedReader (reader); bufferedReader. read ();}}