您的位置:首页 > 其它

工厂模式简单运用

2013-06-10 08:04 344 查看
运用工厂模式实现简单计算

package com.product4;

/**
* 抽象的运算类,包括操作数
* @author Owner
*
*/
public abstract class Operation {

private int num1;

private int num2;

/**
* 运算结果的抽象方法
* @return
*/
public abstract int getResult();

public int getNum1() {
return num1;
}

public void setNum1(int num1) {
this.num1 = num1;
}

public int getNum2() {
return num2;
}

public void setNum2(int num2) {
this.num2 = num2;
}

}


package com.product4;

/**
* 加运算类,实现getResult获取加后的结果
* @author Owner
*
*/
public class AddOperation extends Operation{

@Override
public int getResult() {

return this.getNum1() + this.getNum2();
}

}


package com.product4;

/**
* 减运算类,实现具体的减操作运算
* @author Owner
*
*/
public class SubtractOperation extends Operation{

@Override
public int getResult() {

return this.getNum1() - this.getNum2();
}

}


package com.product4;

/**
* 运算的工厂类,主要生成加/减操作对象
* @author Owner
*
*/
public class OperationFactory {

/**
* 通过操作符号,获取运算对象
* @param oper
* @return
*/
public static Operation getOperation(String oper){
if(oper.equals("+")){
return new AddOperation();
}else if(oper.equals("-")){
return new SubtractOperation();
}else{
return null;
}
}
}


package com.product4;

import java.util.Scanner;

/**
*
* @author Owner
*
*/
public class Customer {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("输入第一个数:");
int num1 = sc.nextInt();

System.out.println("输入运算符:");
String oper = sc.next();

System.out.println("输入第二个数:");
int num2 = sc.nextInt();

//获取运算对象
Operation operation = OperationFactory.getOperation(oper);

operation.setNum1(num1);
operation.setNum2(num2);

System.out.println("运算结果为:"+operation.getResult());
}
}


输出结果为:

输入第一个数:

3

输入运算符:

+

输入第二个数:

2

运算结果为:5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: