This article is your own study notes, welcome reprint, but please specify the source:http://blog.csdn.net/jesson20121020
One problem with the simple factory pattern in the previous section is that class creation relies on the factory class, that is, if you want to expand the program, you must modify the factory class, which violates the closure principle, so, from the design perspective, there are some problems, how to solve? Use the factory method pattern, create a factory interface and create multiple factory implementation classes, so that if you need to add new functionality, add new factory classes directly, without needing to modify the previous code.
Still use the example of the previous section, arithmetic, using the factory method model, the relationship between the parts such as:
Factory method Mode application steps:
1. create a common interface for arithmetic (with simple factory model example):
Public interface Operator{public Double Operate (double d,double e);
2.Create an Add and subtract implementation class (other classes can add their own):
public class Addoperator implements operator{@Overridepublic double Operate (double A, double b) {//TODO auto-generated Me Thod Stubreturn A + b;}}
public class Suboperator implements Operator {@Overridepublic double Operate (double A, double b) {//TODO auto-generated m Ethod Stubreturn A-B;}}
3.provides a factory interface:
Public interface Operatorfactory {public Operator createoperator ();}
4. Create two factory classes:
public class Addfactory implements Operatorfactory {@Overridepublic Operator createoperator () {//TODO auto-generated met Hod Stubreturn new Addoperator ();}}
public class Subfactory implements Operatorfactory {@Overridepublic Operator createoperator () {//TODO auto-generated met Hod Stubreturn new Suboperator ();}}
5. Test class:
public class Factorytest {public static void main (string[] args) {Operatorfactory factory = new Addfactory (); Operator oper = Factory.createoperator (); Double result = oper. Operate (3.6,4.8); SYSTEM.OUT.PRINTLN (result);} }
in this way, in the future when expanding the function of the program, if you want to increase the function of multiplication, you only need to do an implementation class, implementation operatorinterface, at the same time do a factory class, implement the Operatorfactory interface, it is OK, without having to change the ready-made code.
Java design pattern--------The factory method pattern for creating patterns