Simple Factory pattern is the innovative model of the class, also called the Static Factory method pattern, which is responsible for creating instances of other classes by specifically defining a class that is instances that are created typically have a common parent class (or parent interface).
UML diagram for simple Factory mode:
(1) Abstract product role: The parent class of all objects created by the simple factory pattern, note that the parent class here can be an interface or an abstract class, which is responsible for describing common interfaces common to all instances.
(2) Specific products (concrete product) role: The specific instance objects created by a simple factory, which often have a common parent class.
(3) Factory Role (Creator): This is the core of the simple factory model, which is responsible for creating the internal logic of all classes. Of course the factory class must be able to be called outside to create the desired product object.
Code:
(1) Abstract product role:
Package com.liwei.factory.simple; /** @author*/Publicinterface Doll {public void getInfo ();}
(2) Specific product roles
package Com.liwei.factory.simple; public class Barbiedoll implements Doll {@Override public void GetInfo () {System.out.prin TLN ( I am Barbie "
Package com.liwei.factory.simple; Public class Implements Doll { @Override publicvoid getInfo () { System.out.println (" I'm a rag Doll ");} }
(3) Factory role:
Packagecom.liwei.factory.simple; Public classDollfactory { Public StaticDoll getinstance (String name) {if("Barbie". Equals (name)) { return NewBarbiedoll (); }Else if("cloth". Equals (name)) { return NewClothdoll (); }Else{ return NULL; } }}
(4) Test class:
Package com.liwei.factory.simple; Public class Client { publicstaticvoid main (string[] args) { = Dollfactory.getinstance ("cloth"); Doll1.getinfo (); = Dollfactory.getinstance ("Barbie"); Doll2.getinfo (); }}
From the original direct dependence, to become dependent on the factory. It just shifted the dependency relationship.
Simple Factory mode in Java design mode (static Factory method mode)