Java Design Pattern -------- factory method pattern of creation Pattern
This article is my learning notes, welcome to reprint, but please note the Source: http://blog.csdn.net/jesson20121020
One problem with the simple factory model in the previous section is that the creation of the class depends on the factory class. That is to say, if you want to expand the program, you must modify the factory class, which violates the closure principle. Therefore, from the design perspective, how can we solve certain problems? The factory method mode is used to create a factory interface and create multiple factory implementation classes. In this way, you can directly add new factory classes once new functions are required, you do not need to modify the previous code.
We still use the example in the section, the four arithmetic operations, and the factory method mode. The relationship between each part is as follows:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + signature/Signature + CjxwPjxwcmUgY2xhc3M9 "brush: java;"> public interface Operator {public double Operate (double d, double e );}2. Create and add implementation classes (you can add other classes by yourself ):
public class AddOperator implements Operator{@Overridepublic double Operate(double a, double b) {// TODO Auto-generated method stubreturn a + b;}}
public class SubOperator implements Operator {@Overridepublic double Operate(double a, double b) {// TODO Auto-generated method stubreturn a - b;}}
3. Provide 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 method stubreturn new AddOperator();}}
public class SubFactory implements OperatorFactory {@Overridepublic Operator createOperator() {// TODO Auto-generated method 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, if you want to add the multiplication function in the extended functions, you only need to create an implementation class to implement the Operator Interface and a factory class to implement the OperatorFactory interface, instead of modifying the existing code.