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

设计模式之简单工厂模式

2013年08月11日 ⁄ 综合 ⁄ 共 1551字 ⁄ 字号 评论关闭

/**
 * 
 */
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());


	}

}

抱歉!评论已关闭.