Talking about the JAVA Design Pattern -- FactoryMethod and java factory pattern
Reprinted please indicate the source: http://blog.csdn.net/l1028386804/article/details/45440937
I. Overview
Defines an interface used to create objects, so that the subclass determines which class to instantiate. FactoryMethod delays the instantiation of a class to its subclass.
Ii. Applicability3. Participants
1. Product defines the interface of the object created by the factory method.
2. ConcreteProduct implements the Product interface.
3. Creator declares the factory method, which returns an object of the Product type. Creator can also define the default implementation of a factory method, which returns a default ConcreteProduct object. You can call the factory method to create a Product object.
4. ConcreteCreator redefines the factory method to return a ConcreteProduct instance.
IV,
Class Diagram
V. Example
Product
Package com. lyz. design. factorymethod;/*** define an interface Work * @ author liuyazhuang **/public interface Work {/*** definition method */void doWork ();}
ConcreteProduct
Package com. lyz. design. factorymethod;/*** Work interface implementation class * @ author liuyazhuang **/public class TeacherWork implements Work {public void doWork () {System. out. println ("the instructor approves assignments! ");}}
Package com. lyz. design. factorymethod;/*** Work interface implementation class * @ author liuyazhuang */public class StudentWork implements Work {@ Override public void doWork () {System. out. println ("students do homework! ");}}
Creator
Package com. lyz. design. factorymethod; /*** Abstract Factory interface ** @ author liuyazhuang **/public interface IWorkFactory {/*** defines the method for obtaining the Work Instance Object * @ return */Work getWork ();}
ConcreteCreator
Package com. lyz. design. factorymethod;/*** IWorkFactory implementation class * @ author liuyazhuang **/public class StudentWorkFactory implements IWorkFactory {@ Override public Work getWork () {return new StudentWork ();}}
Package com. lyz. design. factorymethod;/*** IWorkFactory implementation class * @ author liuyazhuang **/public class TeacherWorkFactory implements IWorkFactory {@ Override public Work getWork () {return new TeacherWork ();}}
Test
Package com. lyz. design. factorymethod;/*** Test class * @ author liuyazhuang **/public class Test {public static void main (String [] args) {IWorkFactory studentWorkFactory = new StudentWorkFactory (); studentWorkFactory. getWork (). doWork (); IWorkFactory teacherWorkFactory = new TeacherWorkFactory (); teacherWorkFactory. getWork (). doWork ();}}
Result
Students do homework! The instructor approves assignments!