# 简单工厂模式 简单例子

17 篇文章 0 订阅
3 篇文章 0 订阅

## 二、java代码实现

• 问题描述：设计一个用于加减乘除运算的工厂，并提供一个静态方法给客户端运算时使用。
• UML图：

package cn.smileyan.design.easyfactory;
/**
* @title 计算类
* @author Smileyan
* @time: 2018/08/29
* @description 计算类，作为父类
*/
public class Operation {
private double num1;
private double num2;
public double getNum1() {
return num1;
}
public void setNum1(double num1) {
this.num1 = num1;
}
public double getNum2() {
return num2;
}
public void setNum2(double num2) {
this.num2 = num2;
}
// 返回运算结果
public double getResult() {
return 0;
}
}

package cn.smileyan.design.easyfactory;
/**
* @title 加法类
* @author Smileyan
* @time: 2018/08/29
* @description 计算类，加法运算
*/
public class OperationAdd extends Operation {
// 重写父类方法
@Override
public double getResult() {
return this.getNum1()+this.getNum2();
}
}

package cn.smileyan.design.easyfactory;
/**
* @title 除法类
* @author Smileyan
* @time: 2018/08/29
* @description 计算类，除法运算
*/
public class OperationDiv extends Operation {

@Override
public double getResult() {
if(this.getNum2()==0) {
System.out.println("除数不能为0");
return 0;
}
return this.getNum1()/this.getNum2();
}

}

package cn.smileyan.design.easyfactory;
/**
* @title 乘法类
* @author Smileyan
* @time: 2018/08/29
* @description 计算类，乘法运算
*/
public class OperationMul extends Operation {
@Override
public double getResult() {
return this.getNum1()*this.getNum2();
}
}

package cn.smileyan.design.easyfactory;
/**
* @title 减法类
* @author Smileyan
* @time: 2018/08/29
* @description 计算类，减法运算
*/
public class OperationSub extends Operation {
// 重写父类方法
@Override
public double getResult() {
return this.getNum1()-this.getNum2();
}
}


package cn.smileyan.design.easyfactory;
/**
* @title OperationFactory
* @author Smileyan
* @description 工厂类，直接与客户打交道的类
*/
public class OperationFactory {
public static Operation createOperation(String op) {
Operation operation=null;
// 判断并且确认将返回的对象
switch (op) {
case "+":
break;
case "-":
operation=new OperationSub();
break;
case "*":
operation=new OperationMul();
break;
case "/":
operation=new OperationDiv();
break;
default:
break;
}
return operation;
}
}


package cn.smileyan.design.easyfactory;

/**
* @title User
* @author Smileyan
* @description 客户端，即简单工厂的使用者
*/
public class User {
public static void main(String[] args) {
Operation operation=null;
// 此处可以更改为其他运算符 而其他地方可以保持不变
String op="-";
operation = OperationFactory.createOperation(op);
operation.setNum1(99);
operation.setNum2(97);
System.out.println(operation.getResult());
}
}


## 三、总结

• 7
点赞
• 0
评论
• 23
收藏
• 一键三连
• 扫一扫，分享海报

07-09
05-23 1万+

12-21
03-23
10-23 115
05-13 1998
03-21 510
04-15 511
11-20 1万+
03-20 6615
07-02 206
12-26 119
05-31 2911
08-08 80
07-12 107
03-27
©️2021 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。