java 簡單工廠模式(實現一個計算器)

greatmind829發表於2012-06-29
package com.simpleFactory;

/**
 * 運算類
 * @author Administrator
 *
 */
public class Operation {

	
	private double numberA;
	
	private double numberB;

	
	public double getResultValue(){
		return 0.0;
	}
	
	public double getNumberA() {
		return numberA;
	}

	public void setNumberA(double numberA) {
		this.numberA = numberA;
	}

	public double getNumberB() {
		return numberB;
	}

	public void setNumberB(double numberB) {
		this.numberB = numberB;
	}
	
	
	
	
	
}

package com.simpleFactory;

/**
 * 加法實現方式
 * @author Administrator
 *
 */
public class Addition extends Operation {

	
	@Override
	public double getResultValue() {
		return getNumberA() + getNumberB();
	}
}

package com.simpleFactory;

/**
 * 減法實現方式
 * @author Administrator
 *
 */
public class Subtracter extends Operation {

	
	@Override
	public double getResultValue() {
		return getNumberA() - getNumberB();
	}
}

package com.simpleFactory;

/**
 * 簡單工廠類
 * @author Administrator
 *
 */
public class SimpleFactory {

	private Operation operation;
	public Operation factoryOperate (String type ){
		
		if ("+".equals(type)){
			
			operation = new Addition();
		}
		else if ("-".equals(type)){
			
			operation = new Subtracter();
		}
	 return operation;
	}
}

package com.simpleFactory;

/**
 * 簡單工廠類 ,利用反射實現
 * @author Administrator
 *
 */
public class SimpleFactory_reflect {

	private Operation operation;
	public Operation factoryOperate (String classType ){
		
         try {
		operation = (Operation)Class.forName("com.simpleFactory."+classType).newInstance();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	 return operation;
	}
}

package com.simpleFactory;

public class MainRun {

	public static void main(String[] args) {
		
		
		
		SimpleFactory factory = new SimpleFactory();
		Operation operation = factory.factoryOperate("-");
		
		operation.setNumberA(12);
		operation.setNumberB(16);
		
		 //double returnVale  =  operation.getResultValue();
		
		 // System.out.println("returnVale = "+returnVale);
		
		// 利用反射,每次增加新的運算時,不用更改工廠類
		SimpleFactory_reflect factory_reflect = new SimpleFactory_reflect();
		operation = factory_reflect.factoryOperate("Addition");
		
		operation.setNumberA(12);
		operation.setNumberB(16);
		
		double returnVale  =  operation.getResultValue();
		
		System.out.println("returnVale = "+returnVale);
		
	}
}


相關文章