- Implement the same interface as the target object bufferedreader
- Define a variable to remember the target object
- Define a constructor to receive enhanced objects
- Overwrite the method to be enhanced
- For methods that do not want to be enhanced, directly call the method of the target object.
Package CN. liuning. demo; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. reader;/* 1. implement the same interface as the target object bufferedreader 2. define a variable to remember the target object 3. define a constructor to receive enhanced objects 4. overwrite the method to be enhanced. 5. for methods that do not want to be enhanced, directly call the method of the target object. * /// Inheriting bufferedreader is equivalent to implementing its interface. It is a sub-class of bufferedreader and a packaging class of bufferedreader. // when overwriting his method, it is not inherited by the parent class, call all the methods of the target resource, which becomes the packaging class. Public class bufferedreaderwrapper extends bufferedreader {private bufferedreader BR; private int linenum = 1; // The constructor accepts the public bufferedreaderwrapper (bufferedreader in) {super (in ); // display the constructor that calls the parent class. This.br = In;} // overwrite the method to be overwritten. @ override Public String Readline () throws ioexception {// method stub automatically generated by todo // return Super. readline (); the original is to call the Readline () of the parent class; string line = BR. readline (); If (line = NULL) {return line;} return linenum ++ ":" + LINE ;}// other methods inherit from the parent class, you can call the method of the target object directly for methods that do not want to be enhanced .} Package CN. liuning. demo; import Java. io. bufferedreader; import Java. io. filenotfoundexception; import Java. io. filereader; import Java. io. ioexception; public class test {public static void main (string [] ARGs) {try {bufferedreader BR = new bufferedreader (New filereader ("src/CN/liuning/demo/bufferedreaderwrapper. java "); bufferedreaderwrapper wrapper = new bufferedreaderwrapper (BR); string line = NULL; while (Line = wrapper. Readline ())! = NULL) {system. out. println (line) ;}} catch (filenotfoundexception e) {// Catch Block E automatically generated by todo. printstacktrace ();} catch (ioexception e) {// Catch Block E automatically generated by todo. printstacktrace ();}}}
The implementation of the packaging design pattern takes Improving the Readline method in bufferedreader as an Example