has been to the simple factory, factory methods and abstract Factory division is not clear, so in here to clarify the relationship between them, in fact, they belong to the factory model.
1. The first is the simple factory, that is, all objects, regardless of classification, are produced through a factory, the code is as follows:
Computer class
PackagePerson.ismallboy;/*** Computer class *@authorRegis **/ Public classComputer {Privateioutput out; Publiccomputer (Ioutput out) { This. Out =Out ; } Public voidprint () { This. Out.out (); } /** * * @paramargs*/ Public Static voidMain (string[] args) {outputfactory of=Newoutputfactory (); Computer C=NewComputer (Of.getoutput ("Printer")); C.print (); }}
View Code
Ioutput interface
Package Person.ismallboy; /** @author*/Publicinterface ioutput {/** * Output Method * /void out ();
View Code
Betterprinter class
Package Person.ismallboy; Public class Implements ioutput { @Override publicvoid out () { // TODO auto-generated method Stub System.out.println ("Betterprinter");} }
View Code
Printer class
Package Person.ismallboy; Public class Implements ioutput { @Override publicvoid out () { // TODO auto-generated method Stub System.out.println ("Printter"); } }
View Code
Factory class: Outputfactory
PackagePerson.ismallboy;/*** Output Equipment Production plant *@authorRegis **/ Public classOutputfactory { Publicioutput getoutput (String strprinter) {Switch(strprinter) { Case"Printer": return NewPrinter (); Case"Betterprinter": return NewBetterprinter (); default: Break; } return NULL; }}
View Code
The above is a simple factory, I slowly understand. (example from: Li Gang, "Lightweight Java EE Enterprise Application" book)
2. Factory method
Factory method is the subdivision of a simple factory, according to the above example, is the simple factory object is all through a factory to produce products, and the factory method is based on the classification of the establishment of several factories, different factories produce different objects, that is, printer objects produced by the Printerfactory plant, Betterprinter is produced by the Betterprinterfactory factory, so that it can avoid the logic of judgment in the factory, the code is as follows:
......
3. Abstract Factory
Although the factory method can avoid making logical judgments in the factory, the result is that the client is coupled with the specific factory, and at this time, it can be abstracted out, that is, to abstract a factory factory, is to use a factory to produce factory method of the specific factory, So that the client can not be coupled with the specific factory, as long as the factory coupled with the factory can be, this is called the Abstract factory, that is, the factory is also abstracted, the code is as follows:
......
Simple factory, factory method and abstract factory