java设计模式_简单工厂
程序员文章站
2022-07-14 21:41:18
...
/**
* @Title: Calculation.java
* @Package com.wangbiao.design.factory
* @Description: TODO
* @author wangbiao
* @date 2014-9-24 下午11:16:27
* @version V1.0
*/
package com.wangbiao.design.factory;
/**
* @Title: Calculation.java
* @Package com.wangbiao.design.factory
* @Description: TODO
* @author wangbiao
* @date 2014-9-24 下午11:16:27
* @version V1.0
*/
public abstract class Calculation {
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 abstract double getResult();
}
class AddOperation extends Calculation{
@Override
public double getResult() {
return this.getNum1() +this.getNum2();
}
}
class SubOperation extends Calculation{
@Override
public double getResult() {
return this.getNum1()- this.getNum2();
}
}
class MulOperation extends Calculation{
@Override
public double getResult() {
return this.getNum1() * this.getNum2();
}
}
class DivOperation extends Calculation{
@Override
public double getResult() {
if(this.getNum2() != 0){
return this.getNum1() / this.getNum2();
}else{
System.out.println("分母不能为零");
return 0;
}
}
}
/**
* @Title: CalculationFactory.java
* @Package com.wangbiao.design.factory
* @Description: TODO
* @author wangbiao
* @date 2014-9-24 下午11:14:35
* @version V1.0
*/
package com.wangbiao.design.factory;
/**
* @Title: CalculationFactory.java
* @Package com.wangbiao.design.factory
* @Description: TODO
* @author wangbiao
* @date 2014-9-24 下午11:14:35
* @version V1.0
*/
public class CalculationFactory {
Calculation cal = null;
public Calculation operation(int operation){
switch(operation){
case 0:
cal = new AddOperation();
break;
case 1:
cal = new SubOperation();
break;
case 2:
cal = new MulOperation();
break;
case 3:
cal = new DivOperation();
break;
}
return cal;
}
}
/**
* @Title: Client.java
* @Package com.wangbiao.design.factory
* @Description: TODO
* @author wangbiao
* @date 2014-9-24 下午11:19:45
* @version V1.0
*/
package com.wangbiao.design.factory;
/**
* @Title: Client.java
* @Package com.wangbiao.design.factory
* @Description: TODO
* @author wangbiao
* @date 2014-9-24 下午11:19:45
* @version V1.0
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
//+ 0
//- 1
//* 2
/// 3
Calculation cal = new CalculationFactory().operation(0);
cal.setNum1(5);
cal.setNum2(6);
System.out.println(cal.getResult());
}
}
转载于:https://my.oschina.net/u/617909/blog/318348