工厂方法模式

满足开放-封闭原则.
工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行.你想要加功能,本来是改工厂类,而现在是修改客户端.

1
2
3
4
5
6
7
8
9
package factory.method;

/**
* Created by hero on 17-2-17.
*/
public interface Operation {
double getResult(double a, double b);
}

1
2
3
4
5
6
7
8
9
10
11
package factory.method;

/**
* Created by hero on 17-2-17.
*/
public class Add implements Operation {
public double getResult(double a, double b) {
return a + b;
}
}

1
2
3
4
5
6
7
8
9
10
11
package factory.method;

/**
* Created by hero on 17-2-17.
*/
public class Multiplication implements Operation {
public double getResult(double a, double b) {
return a * b;
}
}

1
2
3
4
5
6
7
8
9
package factory.method;

/**
* Created by hero on 17-2-17.
*/
public interface OperationFactory {
Operation createOperation();
}

1
2
3
4
5
6
7
8
9
10
11
package factory.method;

/**
* Created by hero on 17-2-17.
*/
public class AddFactory implements OperationFactory {
public Operation createOperation() {
return new Add();
}
}

1
2
3
4
5
6
7
8
9
10
11
package factory.method;

/**
* Created by hero on 17-2-17.
*/
public class MultiplicationFactory implements OperationFactory {
public Operation createOperation() {
return new Multiplication();
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
package factory.method;

/**
* Created by hero on 17-2-17.
*/
public class Main {
public static void main(String[] args) {
OperationFactory factory = new AddFactory(); //若要改为乘法,只需修改此一处
Operation operation = factory.createOperation();
System.out.println(operation.getResult(1, 2));
}
}