现在的位置: 首页 > 综合 > 正文

大话设计模式之简单工厂模式

2014年09月05日 ⁄ 综合 ⁄ 共 1569字 ⁄ 字号 评论关闭
package simple_factory;

public abstract class Operation {
	private double numberA = 0;
	private double numberB = 0;
	public double getNumberA() {
		return numberA;
	}
	public double getNumberB() {
		return numberB;
	}
	public void setNumberA(double numberA) {
		this.numberA = numberA;
	}
	public void setNumberB(double numberB) {
		this.numberB = numberB;
	}
	public abstract double GetResult() throws Exception;
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Operation oper;
		oper = OperationFactory.createOperation("+");
		oper.setNumberA(1);
		oper.setNumberB(2);
		double result = oper.GetResult();
		System.out.println(result);
	}
}

class OperationAdd extends Operation {
	@Override
	public double GetResult() {
		double result = 0;
		result = this.getNumberA() + this.getNumberB();
		return result;
	}
}

class OperationSub extends Operation {
	@Override
	public double GetResult() {
		double result = 0;
		result = this.getNumberA() - this.getNumberB();
		return result;
	}
}

class OperationMul extends Operation {
	@Override
	public double GetResult() {
		double result = 0;
		result = this.getNumberA() * this.getNumberB();
		return result;
	}
}

class OperationDiv extends Operation {
	@Override
	public double GetResult() throws Exception {
		double result = 0;
		if (this.getNumberB() == 0)
			throw new Exception("除数不能为0");
		result = this.getNumberA() / this.getNumberB();
		return result;
	}
}

class OperationFactory {
	public static Operation createOperation(String operate) {
		Operation oper = null;
		switch (operate)
		{
			case "+":
				oper = new OperationAdd();
				break;
			case "-":
				oper = new OperationSub();
				break;
			case "*":
				oper = new OperationMul();
				break;
			case "/":
				oper = new OperationDiv();
				break;
		}
		return oper;
	}
}

定义Operation抽象类,用于多态生成各种操作,将各种操作解耦为各个类,降低了各种操作代码耦合性。

总体来说,定义一个抽象类,然后若干类继承抽象类,实现抽象方法,工厂会根据需要生成各种子类对象

抱歉!评论已关闭.