简单工厂模式

简单工厂模式实现计算器

计算类代码:

public abstract class Count {
	private double a = 0 ;
	private double b = 0 ;
	public double getB() {
		return b;
	}
	public void setB(double b) {
		this.b = b;
	}
	public double getA() {
		return a;
	}
	public void setA(double a) {
		this.a = a;
	}
	abstract double GetResult() throws Exception;
	
}

编写子类,具体的计算方法,继承计算类:

class Countadd extends Count{
	@Override
	double GetResult() {
		// TODO Auto-generated method stub
		double result = 0 ;
		result = getA() + getB();
		return result;
	}
}
class Countsub extends Count{
	@Override
	double GetResult() {
		// TODO Auto-generated method stub
		double result = 0 ;
		result = getA() - getB();
		return result;
	}
}
这里只给出加法和减法的例子。现在的问题是不知道实例化哪个对象,这里就用到工厂模式,将来如果想增加其他的运算,乘法除法开根平方就很容易了。

编写工厂类:

public class CountFactory {
	public static Count createCount(String value){
		Count cou = null;
		switch (value) {
		case "+":
			cou = new Countadd();
			break;
		case "-":
			cou = new Countsub();
			break;
		}
		return cou;
		
	}
}
这时只输入符号工厂类会实例化出适合的对象,通过多态,返回父类的方法实现计算结果。

更改时,只需添加方法比如Countsub(乘法类),再添加到工厂类的case中。

main方法:

public class jisuanqi {
	@SuppressWarnings("resource")
	public static void main(String[] args){
		try {
			System.out.print("first number:");
			Scanner a1 = new Scanner(System.in);
			double a = a1.nextDouble();
			System.out.print("value:");
			Scanner c1 = new Scanner(System.in);
			String c = c1.next();
			System.out.print("second number:");
			Scanner b1 = new Scanner(System.in);
			double b = b1.nextDouble();
			Count cou;
			cou = CountFactory.createCount(c);
			cou.setA(a);
			cou.setB(b);
			System.out.println("result:"+cou.GetResult());	
		} catch (Exception e) {
			System.out.println("error:"+e.getMessage());
		} 
	}
}
笔记:


scanner sc = new scanner(System.in);

String x = sc.nextLine();





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值