本人还在学习的路上,将自己的疑惑和解答简单的写了一下。如果有错误,感谢大家在下面指出。
简单工厂模式
以加减乘除为例
public class Example{
public static void main (String[] args) throws Exception
{
Operation test = OperationFactory.createoperation('+');
test.number_A = 1;
test.number_B = 2;
System.out.println(test.getResult());
}
}
class Operation{
public double number_A;
public double number_B;
public double getResult() throws MyException{
return 0d;
}
}
class OperationAdd extends Operation{
public double getResult(){
return number_A + number_B;
}
}
class OperationSub extends Operation{
public double getResult(){
return number_A - number_B;
}
}
class OperationMul extends Operation{
public double getResult(){
return number_A * number_B;
}
}
class OperationDiv extends Operation{
public double getResult() throws MyException{
if (number_B == 0){
throw new MyException("除数不能为零!");
}else{
return number_A / number_B;
}
}
}
class OperationFactory{
public static Operation createoperation(char str) throws MyException{
switch (str){
case '+':
return new OperationAdd();
case '-':
return new OperationSub();
case '*':
return new OperationMul();
case '/':
return new OperationDiv();
default:
throw new MyException("无效符号!");
}
}
}
class MyException extends Exception{
public MyException(String str){
super(str);
}
}
策略模式
public class Example{
public static void main (String[] args) throws Exception
{
OperationStrategy test = new OperationStrategy('+');
System.out.println(test.getResult(1,2));
}
}
class Operation{
public double number_A;
public double number_B;
public double getResult() throws MyException{
return 0d;
}
}
class OperationAdd extends Operation{
public double getResult(){
return number_A + number_B;
}
}
class OperationSub extends Operation{
public double getResult(){
return number_A - number_B;
}
}
class OperationMul extends Operation{
public double getResult(){
return number_A * number_B;
}
}
class OperationDiv extends Operation{
public double getResult() throws MyException{
if (number_B == 0){
throw new MyException("除数不能为零!");
}else{
return number_A / number_B;
}
}
}
class OperationStrategy{
Operation op = new Operation();
public OperationStrategy(char str) throws MyException{
switch (str){
case '+':
op = new OperationAdd();
break;
case '-':
op = new OperationSub();
break;
case '*':
op = new OperationMul();
break;
case '/':
op = new OperationDiv();
break;
default:
throw new MyException("无效符号!");
}
}
public double getResult(double number_A, double number_B) throws MyException{
op.number_A = number_A;
op.number_B = number_B;
return op.getResult();
}
}
class MyException extends Exception{
public MyException(String str){
super(str);
}
}
两者的差异
1.简单工厂模式侧重点返回一个对象(如简单工厂模式代码中OperationFactory类返回的是一个Operation对象),而策略模式侧重返回一个方法(如策略模式代码中调用OperationStrategy类中的getResult()方法返回一个Operation对象的一个方法)
2.策略模式相对来说耦合度更低,将不需要让客户了解的类(也就是例子中Operation类)封装起来。