1. Definition
Defines an interface for creating an object, letting subclasses decide which class to instantiate, FactoryMethod the instantiation of a class to its subclasses.
2. Awareness Map
3. Code examples
Lenovo factory creates Lenovo's computer, Dell creates Dell's computer
1) Computer interface
/** * Computer interface * [email protected] * */ Public Interface Computer { /** * Description --and a word about @param Description Descriptive language */ Public void describe (String description);}
2). Dell Computer
/** * Dell PC * [email protected] * */ Public class Implements Computer { @Override publicvoid describe (String description) { System.out.println (description); } }
3). Lenovo Computer
/** * Lenovo Computer * [email protected] * */ Public class Implements Computer { @Override publicvoid describe (String description) { System.out.println (description); } }
4). Computer Factory
/*** Computer Factory * [email protected] * December 25, 2017*/ Public classComputerfactory { Public StaticComputer Buildcomputer (String pcname) {if("Dell". Equalsignorecase (Pcname))return NewDellcomputer (); if("Lenovo". Equalsignorecase (Pcname))return NewLenovocomputer (); return NULL; }}
5). Computer Operation class
/** * Computer Operation class, Call factory to create PC * [email protected] * December 25, 2017 */ public class Computeroperator {
/** * Create PC * @param pcname computer name * @param Span style= "COLOR: #008000" > description computer description */ public void Createcomputer ( String pcname,string description) {computerfactory.buildcomputer (pcname). Describe (description); }}
6). Client class
/** * client * [email protected] * */ Public class Client { publicstaticvoid main (string[] args) { New computeroperator (); Computeroperation.createcomputer ("Lenovo", "I am Lenovo"); Computeroperation.createcomputer ("Dell", "I Am Dell");} }
7). Results
I'm Lenovo, I'm Dale.
4. Summary
When to choose?
1). One interface multiple implementations, but do not know the specific implementation of which, the subclass to specify
2). The system design itself assigns the implementation class to the subclass
Design patterns of factory methods for Java design patterns