Strategy 设计模式 策略模式 超靠谱原代码讲解

先来假设一种情,我们需要向三种不同的客户做出不同的报价,一般来说要肿么设计呢,是不是马上会想到用IF,没有错,对于这种情况,策略模式是最好的选。大家可以这么理解,如果有情况需要用到大量的IF,那你用策略模式就一定没有错了。好了,不多说,直接上代码

先建一个Customer,放三种不同的客户类型

package Customer;

import Inter.Strategy;

public class LargeCustomer implements Strategy{
	
	public double calcPrice(double goodsPrice){
		System.out.println("对于大客户,统一折扣10%");
		return goodsPrice*(1-0.1);
	}
}

package Customer;

import Inter.Strategy;

public class NormalCustomer implements Strategy{
	/**
	 * 
	 * 具体算法的实现,为VIP1计算价格
	 * 
	 * */
	public double calcPrice(double goodsPrice){
		System.out.println("对于新客户或是普通客户,没有折扣");
		return goodsPrice;
		
	}
}

package Customer;

import Inter.Strategy;

public class oldCustomer implements Strategy{
	
	public double calcPrice(double goodsPrice){
		System.out.println("对于老客户,统一折扣5%");
		return goodsPrice*(1-0.05);
	}
}

再建一个接口Inter

package Inter;

public interface Strategy {
/*
 * 
 * 
 * **/
	public double calcPrice(double goodsPrice);
}

再来一个实现业务的报价系统

package Price;

import Inter.Strategy;

public class Price {
	private Strategy strategy = null;
	
	public Price (Strategy aStrategy){
		this.strategy = aStrategy;
	}
	
	public double quote(double goodsPrice){
		return this.strategy.calcPrice(goodsPrice);
	}
}

是不是很简单,接下来就可以调式了

package Test;

import Customer.LargeCustomer;
import Inter.Strategy;
import Price.Price;

public class Clients {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	   //实例化并使用LargeCustomer策略装载到策略器strategy当中
		Strategy strategy = new LargeCustomer();
		
		//实例化报价者ctx,然后把已经装有策略的策略器strategy给它
		Price ctx = new Price(strategy);
		
		//正式给报价者ctx输值2000,CTX会跟据已经装有策略的的策略器去执行策略,得出来的值塞给quote,其实不塞进接用该函数也可以显示值,大家懂的
		double quote = ctx.quote(2000);
		
		System.out.println("向客户报价:" + quote);
		
		
	}

}


posted on 2014-03-06 15:58  王大王  阅读(137)  评论(0编辑  收藏  举报

导航