当处理同一个对象有多个处理算法的时候,使用一个策略对象来选择处理算法。
例子:
对于客户的优惠率。
算法实现统一的接口:
public interface Strategy { public double getPrice(double standarPrice);//获取计算价格的算法 }
具体算法,实现类1:
class NewCustomerFewStrategy implements Strategy{ @Override public double getPrice(double standarPrice) { System.out.println("新顾客,少量购买,不打折"); return standarPrice; } }
实现类2:
class NewCustomerManyStrategy implements Strategy{ @Override public double getPrice(double standarPrice) { System.out.println("新顾客,大量购买,九五折"); return standarPrice; } }
实现类3:
class OldCustomerFewStrategy implements Strategy{ @Override public double getPrice(double standarPrice) { System.out.println("老客户,少量购买,九折"); return standarPrice*0.9; } }
实现类4:
class OldCustomerManyStrategy implements Strategy{ @Override public double getPrice(double standarPrice) { System.out.println("老客户,大量购买,八折"); return standarPrice*0.8; } }
策略对象:持有一个算法对象的引用,即可调用实际的算法,实现了处理对象与被处理对象的分类。
public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } //可以设置指定算法 public void setStrategy(Strategy strategy) { this.strategy = strategy; } //价格算法 public void pringPrice(double s){ System.out.println("折后价:"+strategy.getPrice(s)); } }
测试:
public class Client { public static void main(String[] args) { //顾客类型 Strategy s1 = new OldCustomerFewStrategy(); //策略对象,根据客户类型选取算法 Context c1= new Context(s1); //执行策略 c1.pringPrice(998); } }
测试结果:
标签:策略,double,模式,Strategy,算法,standarPrice,strategy,public From: https://www.cnblogs.com/lurenjia-bky/p/16928128.html