设计模式之简单工厂模式
来源:互联网 发布:南京千米网络怎么样 编辑:程序博客网 时间:2024/06/05 03:37
今天看了简单工厂模式,总体来说这种模式是这样子的:
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());
}
}
- 设计模式 之简单工厂+ 工厂模式
- 设计模式之简单工厂设计模式
- 设计模式之简单工厂模式,工厂模式,策略模式
- 设计模式 之 简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂.
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- 设计模式之简单工厂
- mySQL之简单命令
- Android7.0 自动更新适配,包解析异常
- spring BeanFactoryPostProcessor和BeanPostProcessor解析
- 大数据的核心价值
- 【Python】Matplotlib画图(三)——分段函数
- 设计模式之简单工厂模式
- Autofac tutorial 1
- 微信发送文本消息
- HDU5663 Hillan and the girl[莫比乌斯反演]
- Python基础
- Charles 使用简介
- swager中注解的用途
- BZOJ 2733 [HNOI2012]永无乡 Treap + 并查集
- leetcode 669. Trim a Binary Search Tree