设计模式之简单工厂模式




/**
 * 
 */
package com.handy.dp.sf;

/**
 * @author handy
 * 
 */
public abstract class Operation {
	private int numberA;
	private int numberB;

	/**
	 * @return the numberA
	 */
	public int getNumberA() {
		return numberA;
	}

	/**
	 * @param numberA
	 *            the numberA to set
	 */
	public void setNumberA(int numberA) {
		this.numberA = numberA;
	}

	/**
	 * @return the numberB
	 */
	public int getNumberB() {
		return numberB;
	}

	/**
	 * @param numberB
	 *            the numberB to set
	 */
	public void setNumberB(int numberB) {
		this.numberB = numberB;
	}

	public abstract int getRusult();

}

/**
 * 
 */
package com.handy.dp.sf;

/**
 * @author handy
 * 
 */
public class OperationFactory {
	Operation oper;

	public OperationFactory(char operator) {
		int operatorInt = operator;

		switch (operatorInt) {
		case 43:
			oper = new OperationAdd();
			break;
		case 45:
			oper = new OperationSub();
			break;
		case 42:
			oper = new OperationMul();
			break;
		case 47:
			oper = new OperationDiv();
			break;

		}
	}
}

/**
 * 
 */
package com.handy.dp.sf;

/**
 * @author handy
 *
 */
public class OperationAdd extends Operation {

	@Override
	public int getRusult() {
		// TODO Auto-generated method stub
		return getNumberA()+getNumberB();
	}

}

/**
 * 
 */
package com.handy.dp.sf;

/**
 * @author handy
 *
 */
public class OperationSub extends Operation{
	@Override
	public int getRusult() {
		// TODO Auto-generated method stub
		return getNumberA()-getNumberB();
	}
}

/**
 * 
 */
package com.handy.dp.sf;

/**
 * @author handy
 * 
 */
public class TestSimpleFactory {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		OperationFactory of1 = new OperationFactory('+');
		of1.oper.setNumberA(18);
		of1.oper.setNumberB(3);
		System.out.println(of1.oper.getRusult());
		OperationFactory of2 = new OperationFactory('-');
		of2.oper.setNumberA(18);
		of2.oper.setNumberB(3);
		System.out.println(of2.oper.getRusult());


	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值