策略模式 Idea
策略模式 Strategy
策略模式是一种行为型模式,它将对象和行为分开,将行为定义为 一个行为接口 和 具体行为的实现。策略模式最大的特点是行为的变化,行为之间可以相互替换。每个if判断都可以理解为就是一个策略。
封装计算价格策略模式接口类
package com.learn.strategy;
/**
* 场景: 拼车、快车、商务车
* 三种计费方式,就是行为,可以根据不同行为的计算方式计算不同的费用
* 抽象成一个价格计算接口类
* 定义一个PriceContext环境类,启承上启下的封装作用,负责和策略接口类交互
* 具体的打车场景实现PriceStrategy 接口类
*/
public interface PriceStrategy {
Double calculatePrice(Double price);
}
计算价格上下文环境类
package com.learn.strategy;
/**
* PriceContext环境类
*/
public class PriceContext {
private PriceStrategy priceStrategy;
public PriceContext(PriceStrategy priceStrategy) {
this.priceStrategy = priceStrategy;
}
public Double calculatePrice(Double price) {
return priceStrategy.calculatePrice(price);
}
}
场景1: 拼车
package com.learn.strategy;
/**
* 拼车场景
*/
public class CarPool implements PriceStrategy {
@Override
public Double calculatePrice(Double price) {
return price * 0.5;
}
public static void main(String[] args) {
CarPool carPool = new CarPool();
PriceContext carContext = new PriceContext(carPool);
System.out.println(carContext.calculatePrice(10D));
}
}
场景二: 快车
package com.learn.strategy;
/**
* 快车场景
*/
public class ExpressTrain implements PriceStrategy{
@Override
public Double calculatePrice(Double price) {
return price * 1.5;
}
public static void main(String[] args) {
ExpressTrain expressTrain = new ExpressTrain();
PriceContext expressContext = new PriceContext(expressTrain);
System.out.println(expressContext.calculatePrice(10D));
}
}
场景三: 商务车
package com.learn.strategy;
/**
* 商务车
*/
public class BusinessCar implements PriceStrategy{
@Override
public Double calculatePrice(Double price) {
return price * 3;
}
public static void main(String[] args) {
BusinessCar businessCar = new BusinessCar();
PriceContext businessContext = new PriceContext(businessCar);
System.out.println(businessContext.calculatePrice(10D));
}
}