Factory method Definition:
1 Factory Method2 3 Overview4 defines an interface for creating objects, letting subclasses decide which class to instantiate. FactoryMethod defers the instantiation of a class to its subclasses. 5 6 Applicability7 1. When a class does not know the class of the object it must create. 8 9 2when a class wants to specify the object it creates by its subclasses. Ten One 3when a class delegates the responsibility of creating an object to one of several helper subclasses, and you want to set which helper subclass is the agent this information is localized. A participants - 1. Product - an interface that defines the objects created by the factory method. the - 2. Concreteproduct - implement the Product interface. - + 3. Creator - declares a factory method that returns an object of type product. + Creator can also define a default implementation of a factory method that returns a default Concreteproduct object. A You can call the factory method to create a product object. at - 4. Concretecreator -Redefine the factory method to return a concreteproduct instance.
Test code:
1 Public classTest {2 3 Public Static voidMain (string[] args) {4Iworkfactory studentworkfactory =Newstudentworkfactory ();5 studentworkfactory.getwork (). DoWork ();6 7Iworkfactory teacherworkfactory =Newteacherworkfactory ();8 teacherworkfactory.getwork (). DoWork ();9 }Ten One}
1 Public Interface iworkfactory {23work getwork (); 4 }
1 public interface work { 2 void DoWork (); 4 }
1 public class Studentworkfactory implements Iworkfactory { 2 3 public work getwork () { 4 return new Studentwork (); 5 6 7 }
1 Public class Implements Work {23 Public void doWork () {4 SYSTEM.OUT.PRINTLN ("Students do homework!") ); 5 }67 }
1 Public class Implements iworkfactory {23 Public Work Getwork () {4 return New teacherwork (); 5 }67 }
1 Public class Implements Work {23 Public void doWork () {4 System.out.println ("The teacher approves the work!") ); 5 }67 }
Java Design Patterns--creating patterns--factory methods