文章来源地址https://www.toymoban.com/news/detail-522765.html
public interface Strategy {
public double getPrice(double standardPrice);
}
public class OldCustomManyStrategy implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("老客户大批量,打8折");
return standardPrice*0.8;
}
}
public class OldCustomFewStrategy implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("老客户小批量,打85折");
return standardPrice*0.85;
}
}
public class NewCustomManyStrategy implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("新客户大批量,打9折");
return standardPrice*0.9;
}
}
public class NewCustomFewStrategy implements Strategy{
@Override
public double getPrice(double standardPrice) {
System.out.println("新客户小批量,不打折");
return standardPrice;
}
}
/**
* 负责和具体的算法交互
* 如此,具体的算法和直接的客户端调用分离了,使得算法可以独立与客户端独立的变化
* 如果使用Spring的依赖注入功能,可以通过配置文件动态的注入不同的策略对象,动态的切换不同的算法
* @author tqq
* @date 2021-04-02-10:39
*/
public class Context {
private Strategy strategy;//当前采用的算法对象
//通过构造器注入
public Context(Strategy strategy) {
this.strategy = strategy;
}
//通过set注入
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void printPrice(double s){
System.out.println("你的报价为:"+strategy.getPrice(s));
}
}
public class Client{
public static void main(String[] args) {
Strategy s1 = new OldCustomFewStrategy();
Context context = new Context(s1);
context.printPrice(100);
}
}
文章来源:https://www.toymoban.com/news/detail-522765.html
到了这里,关于策略模式Strategy的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!