大话设计模式读书笔记1 简单工厂模式

试着用java实现了一下 废话少说上代码

operator.class

package org.ustc.simplefactory;

public class Operator {	
	int num1;
	int num2;
	
	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;
	}

	public double getResult(){
		return 0;
	}
}

几个继承类

package org.ustc.simplefactory;
//实现加法
public class AddOperator extends Operator {

	@Override
	public double getResult() {
		// TODO Auto-generated method stub
		return num1+num2;
	}

}

package org.ustc.simplefactory;

public class DevideOperator extends Operator {

	@Override
	public double getResult() {
		// TODO Auto-generated method stub
		double d = 0.0;
		try{
			d = num1/num2;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return d;
	}

}
package org.ustc.simplefactory;

public class MinusOperator extends Operator {

	@Override
	public double getResult() {
		// TODO Auto-generated method stub
		return num1-num2;
	}

}

package org.ustc.simplefactory;

public class MutipleOperator extends Operator {

	@Override
	public double getResult() {
		// TODO Auto-generated method stub
		return num1*num2;
	}

}
工厂方法类
package org.ustc.simplefactory;

public class SimpleFacetory {
	
	public static Operator choseOperator(char c){
		Operator operator = null;
		switch(c){
		case '+':
			operator = new AddOperator();
			break;
		case '-':
			operator = new MinusOperator();
			break;
		case '*':
			operator = new MutipleOperator();
			break;
		case '/':
			operator = new DevideOperator();
			break;
		}
		return operator;
	}
}

package org.ustc.simplefactory;

public class Main {
	public static void main(String[] args) {
		Operator operator = SimpleFacetory.choseOperator('/');
		operator.setNum1(1);
		operator.setNum2(0);
		System.out.println("结果是:"+operator.getResult());
	}
}


UML图


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值