1、定义
策略模式:定义一系列算法,把它们封装起来,并且使它们可以互相替换
写法
public interface IMemberStrategy {
//打折
double discount(double price);
}
public class AdvancedMemberStrategy implements IMemberStrategy {
@Override
public double discount(double price) {
return price * 0.8;
}
}
public class IntermediateMemberStrategy implements IMemberStrategy {
@Override
public double discount(double price) {
return price * 0.9;
}
}
public class PrimaryMemberStrategy implements IMemberStrategy {
@Override
public double discount(double price) {
return price * 1;
}
}
public class Price {
private IMemberStrategy strategy;
public Price(IMemberStrategy strategy){
this.strategy = strategy;
}
public double quote(double booksPrice){
return strategy.discount(booksPrice);
}
}
/**
* 策略模式
* 关注点在于行为的选择
* 解决swich-case
*/
public class TestMain {
public static void main(String[] args) {
Price price = new Price( new PrimaryMemberStrategy() );
price.quote( 100 );
Price price1 = new Price( new IntermediateMemberStrategy() );
price.quote( 100 );
Price price2 = new Price( new AdvancedMemberStrategy() );
price.quote( 100 );
}
}