码迷,mamicode.com
首页 > 其他好文 > 详细

简单工厂模式

时间:2014-07-24 17:36:46      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:工厂模式   设计模式   

简单工厂模式(Factory Method):定义一个用于创建对象的接口,让子类决定将哪一个类实例化。Factory Method使一个类的实例化延迟到其子类。

package gof23;

public class SimpleFactoryTest {
	public static void main(String[] args) {
		Operation oper = null;
		oper = OperationFactory.createOperate("+");
		oper.numA = 2;
		oper.numB = 0;
		System.out.println(oper.getResult());
		oper = OperationFactory.createOperate("-");
		oper.numA = 2;
		oper.numB = 0;
		System.out.println(oper.getResult());
		oper = OperationFactory.createOperate("*");
		oper.numA = 2;
		oper.numB = 0;
		System.out.println(oper.getResult());
		oper = OperationFactory.createOperate("/");
		oper.numA = 2;
		oper.numB = 0;
		System.out.println(oper.getResult());
	}
}

class OperationFactory {
	public static Operation createOperate(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;
	}
}

class Operation {
	protected double numA = 0;
	protected double numB = 0;
	public double getNumA() {
		return numA;
	}
	public void setNumA(double numA) {
		this.numA = numA;
	}
	public double getNumB() {
		return numB;
	}
	public void setNumB(double numB) {
		this.numB = numB;
	}
	//可被重写的方法,获取运算结果
	public double getResult() {
		double result = 0;
		return result;
	}
}

/*
 * 加法
 */
class OperationAdd extends Operation{
	@Override
	public double getResult() {
		double result = 0;
		result = numA + numB;
		return result;
	}
}

/*
 * 减法
 */
class OperationSub extends Operation{
	@Override
	public double getResult() {
		double result = 0;
		result = numA - numB;
		return result;
	}
}
/*
 * 乘法
 */
class OperationMul extends Operation{
	@Override
	public double getResult() {
		double result = 0;
		result = numA * numB;
		return result;
	}
}

/*
 * 除法
 */
class OperationDiv extends Operation{
	//注意除数不能为0
	@Override
	public double getResult() {
		double result = 0;
		if(Math.abs(numB - 0.0) < 0.00000001) {
			System.out.println("除数不能为0");
			return -1;
		}
		result = numA / numB;
		return result;
	}
}

运行结果:

2.0
2.0
0.0
除数不能为0
-1.0


简单工厂模式,布布扣,bubuko.com

简单工厂模式

标签:工厂模式   设计模式   

原文地址:http://blog.csdn.net/hjiam2/article/details/38085723

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!