今天看了简单工厂模式,总体来说这种模式是这样子的:
1、首先定义一个接口,这个接口里面定义了一些方法;
2、有好几个类实现了这个接口;
3、根据需求,通过一个工厂类来生成想要的一个类,这个类属于第2步里面说的类;
下面通过实现一个简单的加减乘除的功能来说明这个模式:
1:
定义一个接口:
public interface Operation
{
public double calc();
}
2:
分别定义加减乘除四个类,并且这四个类实现了Operation这个接口:
public class AddOperation implements Operation
{
public double A;
public double B;
public AddOperation(double a, double b)
{
A = a;
B = b;
}
@Override
public double calc()
{
return A + B;
}
}
public class SubOperation implements Operation
{
public double A;
public double B;
public SubOperation(double a, double b)
{
A = a;
B = b;
}
@Override
public double calc()
{
return A - B;
}
}
public class MulOperation implements Operation
{
public double A;
public double B;
public MulOperation(double a, double b)
{
A = a;
B = b;
}
@Override
public double calc()
{
return A * B;
}
}
public class DivOperation implements Operation
{
public double A;
public double B;
public DivOperation(double a, double b)
{
A = a;
B = b;
}
@Override
public double calc()
{
double result = 0;
if (B == 0) {
try
{
throw new Exception("除数不能为零。");
} catch (Exception e)
{
e.printStackTrace();
}
}
else {
result = A / B;
}
return result;
}
}
3:接着定义工厂类:
public class OperationFactory
{
public static Operation getOperation(String type, double A, double B) {
Operation oper = null;
switch (type) {
case "+" :
oper = new AddOperation(A, B);
break;
case "-" :
oper = new SubOperation(A, B);
break;
case "*" :
oper = new MulOperation(A, B);
break;
case "/" :
oper = new DivOperation(A, B);
break;
default :
System.out.println("不能识别该操作符!");
}
return oper;
}
}
这样子,就完成了一个简单的工厂模式了。
下面是测试代码:
public class Client
{
public static void main(String[] args)
{
Operation oper_add = OperationFactory.getOperation("+", 2, 3);
System.out.println(oper_add.calc());
Operation oper_sub = OperationFactory.getOperation("-", 5, 3);
System.out.println(oper_sub.calc());
Operation oper_mul = OperationFactory.getOperation("*", 2,3);
System.out.println(oper_mul.calc());
Operation oper_div = OperationFactory.getOperation("/", 4,3);
System.out.println(oper_div.calc());
}
}