Since the learning design pattern, has emphasized the interface programming, relies on the abstraction rather than the concrete, but every time sees new to be out of the object, is not to have the question? How could it be this way? It seems that Java only provides this way of generating objects from a class, without suspecting that Java really has only this basic way of generating objects, but we can abstract it so that our calling code generates objects on a more advanced level and gets objects based on different business requirements.
There are three factory models, one is a simple factory, another is a factory method, and the last is an abstract factory.
Simple factories are generally written as static factories, as below,
Packagecom.csshu.simple;/*** Factory class code, just a simple answer based on the conditions to generate the code, and finally return an object *@authorShujianhua **/ Public classSimeple {Private StaticPizza Pizza; Public StaticPizza Create (String type) {if(Type.equals ("1") ) {Pizza=NewPizza1 (); } Else if(Type.equals ("2") ) {Pizza=NewPizza2 (); }Else if(Type.equals ("3") ) {Pizza=NewPizza3 (); }Else if(Type.equals ("4") ) {Pizza=NewPizza4 (); }Else if(Type.equals ("5") ) {Pizza=NewPizza5 (); }Else if(Type.equals ("6") ) {Pizza=NewPizza6 (); } returnPizza; }} Packagecom.csshu.simple; Public classPizza { Public voidspeak () {System.out.println ("I am a pizza parent"); }} Packagecom.csshu.simple; Public classPizza1extendspizza{@Override Public voidspeak () {System.out.println ("1"); }} Packagecom.csshu.simple; Public classTest { Public Static voidMain (string[] args) {Pizza Pizza= Simeple.create ("1"); Pizza.speak (); }}
As above, that is the method of simple factory, because the general writing static class, so cannot inherit, cannot change the method through the subclass.
The factory method makes a little bit of abstraction, pushing the build to deferred to the child class generation.
Abstract factory, the main function is to a large number of objects of the collection, mainly object aspects.
Factory method and abstract factory to be continued---
Design mode four Factory mode 1