策略模式

策略模式:它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响使用算法的客户。

package com.jshx.cash;

import com.jshx.operation.Operation;
import com.jshx.operation.OperationAdd;
import com.jshx.operation.OperationDiv;
import com.jshx.operation.OperationMul;
import com.jshx.operation.OperationSub;

public class CashOperation {
	Operation oper;
	
	/**
	 * 将实例化具体策略的过程在些实现。简单工厂的应用。
	 * @param operate
	 */
	public CashOperation(String operate){
		char[] ch=operate.toCharArray();
		switch(ch[0]) {
		case '+':
			oper = new OperationAdd();
			break;
		case '-':
			oper = new OperationSub();
			break;
		case '*':
			oper = new OperationMul();
			break;
		case '/':
			oper = new OperationDiv();
			break;
		}
	}
	public double getResult(double numberA,double numberB) throws Exception{
		oper.setNumberA(numberA);
		oper.setNumberB(numberB);
		return oper.getResult();
	}
}


package com.jshx.cash;

public class CashOperationTest {
	public static void main(String[] args) throws Exception {
		CashOperation co = new CashOperation("+");
		double result = co.getResult(1,2);
		System.out.println(result);
	}
}


简单工厂模式与策略模式的比较
//简单工厂模式
Operation oper = OperationFactory.createOperation("-");
double result = oper.getResult(...)


//策略模式与简单工厂模式结合的用法
CashOperation co = new CashOperation("+");
double result = oper.getResult(...)


简单工厂需要让action认识两个类,Operation 和OperationFactory,而策略模式与简单工厂模式结合的用法,只需要认识一个类CashOperation ,实现了松耦合。

你可能感兴趣的:(企业应用)