The following is a java4android video tutorial from marschen.
Main content of this set
1. Why use interfaces.
2. Factory method mode.
The interface actually defines a standard.
Implementation interface.
Instance 1 is as follows.
A printer interface, an hpprinter class, a canonprinter class, and a test class.
// Printer interface printer {public void open (); Public void close (); Public void print (string S );}
// Hpprinter class hpprinter implements printer {public void open () {system. out. println ("HP Open");} public void close () {system. out. println ("HP close");} public void print (string s) {system. out. println ("HP print --->" + S );}}
// Canonprinter class canonprinter implements printer {private void clean () {system. out. println ("canon priter clean");} public void close () {This. clean (); system. out. println ("canon close");} public void open () {system. out. println ("canon open");} public void print (string s) {system. out. println ("canon print --->" + S );}}
Class test {public static void main (string ARGs []) {// based on the user's selection, generate the corresponding printer object // and convert it to the printer type upwards. // Printer getprinter (INT flag); printer = NULL; int flag = 1; if (flag = 0) {printer = new hpprinter (); // upward transformation} else if (flag = 1) {printer = new canonprinter (); // upward transformation} printer. open (); printer. print ("test"); printer. close ();}}
There are still many problems with the above program. In the test class, the code for generating objects is repeated.
Use
Simple static factory method mode.
Printer
| Printerfactory
Hpprinter canonprinter
Modify the above Code.
Add a printerfactory class
Class printerfactory {public static printer getprinter (INT flag) {printer = NULL; If (flag = 0) {printer = new hpprinter (); // upward transformation} else if (flag = 1) {printer = new canonprinter (); // upward transformation} else if (flag = 2) {printer = new xxxprinter (); // up transition} return printer ;}}
In the test class, do this.
Class test {public static void main (string ARGs []) {// based on the user's selection, generate the corresponding printer object // and convert it to the printer type upwards. Int flag = 2; printer = printerfactory. getprinter (FLAG); printer. open (); printer. Print ("test"); printer. Close ();}}
To add a printer, you only need to add a printer, for example, adding a xxxprinter printer.
// Xxxprinter class xxxprinter implements printer {public void open () {system. out. println ("XXX open");} public void close () {system. out. println ("XXX close");} public void print (string s) {system. out. println ("XXX print --->" + S );}
Add.
Else if (flag = 2) {printer = new xxxprinter (); // upward transformation}
No need to modify the printer call code...