Factory method Mode (Factory) definition
Defines an interface for creating objects, letting subclasses decide which class to instantiate. The factory method defers a class to its subclasses.
UML Class Diagram
Composition
1) Abstract Factory Role (Creator): This is the core of the factory method pattern, which is not related to the application. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.
2) Specific factory role (Concretecreator): It contains code related to the specific business logic. Called by the application to create an object that corresponds to a specific product.
3) Abstract Product role: It is the parent of a specific product inheritance or an implemented interface. In Java, there are generally abstract classes or interfaces to implement.
4) Specific product roles (CONCRETEPRODUCT): The object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.
Example
A BMW manufacturing plant that can manufacture various models of BMW.
package com.csdhsm.designpattem.factory ; /** * @Title: Bmw.java * @Description: Creator All BMW inherits from the class * @author : Han * @date: June 20, 2016 PM 5:46:56 */ abstract public class BMW { public BMW () {}}
package com.csdhsm.designpattem.factory ; /** * @Title: Bmw320.java * @Description: Model 320 BMW * @author : Han * @date: June 20, 2016 PM 5:48:05 */ public class BMW320 extends BMW { public BMW320 () {System.out.println ( Manufacturing--"BMW320"
Package com.csdhsm.designpattem.factory; /** * @Title: bmw523.java @author: Han * @date: June 20, 2016 PM 5:48:35 */public classextends BMW {public BMW523 () { System.out.println ("Manufacturing--" BMW523 ");} }
Abstract product
Package com.csdhsm.designpattem.factory; /** * @Title: factorybmw.java @author: Han * @date: June 20, 2016 5:49:24 */ Public Interface FACTORYBMW { BMW createbmw ();}
Concreteproduct
package com.csdhsm.designpattem.factory ; /** * @Title: Factorybmw320.java * @Description: Factory of BMW320 * @author : Han * @date: June 20, 2016 PM 5:50:29 */ public class FactoryBMW320 Span style= "color: #0000ff;" >implements FACTORYBMW {@Override BMW CREATEBMW () { return new BMW320 (); }}
Package com.csdhsm.designpattem.factory; /** * @Title: factorybmw523.java @author: Han * @date: June 20, 2016 PM 5 : 50:12 */public classimplements FACTORYBMW { @Override Public BMW createbmw () { returnnew BMW523 (); }}
Client
Package com.csdhsm.designpattem.factory; Public class Solution { publicstaticvoid main (string[] args) { new FactoryBMW320 (); FACBMW.CREATEBMW (); New FactoryBMW523 (); FACBMW.CREATEBMW (); }}
Results
Disadvantages
The addition of factory methods has multiplied the number of objects.
Design mode (8)-----Factory Method mode