Java设计模式——策略模式
前言
在我们工作中经常会遇到if else多重判断的情况,每种具体的情况都需要单独写一个if去判断,如果后期需求变化需要重新去修改if判断条件,比较麻烦这时候可以使用策略模式.
一.策略模式简介
策略模式:策略模式是一种行为型模式,它将对象和行为分开,将行为定义为 一个行为接口 和 具体行为的实现。策略模式最大的特点是行为的变化,行为之间可以相互替换。每个if判断都可以理解为就是一个策略。本模式使得算法可独立于使用它的用户而变化.
这个模式涉及到三个角色:
- 环境(Context)角色:持有一个Strategy的引用。
- 抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
- 具体策略(ConcreteStrategy)角色:包装了相关的具体算法或行为。
策略模式的案例代码如下:
针对不同会员等级,商品折扣不相同,普通打9.5折,会员打9折。
策略:
public interface Strategy {
/**
* 策略方法
*/
void strategyPrice(Double price);
}
具体策略:
public class UserStrategy implements Strategy {
@Override
public Double strategyPrice(Double price) {
price=price*0.95;
return price;
}
}
public class VipUserStrategy implements Strategy {
@Override
public Double strategyPrice(Double price) {
price=price*0.90;
return price;
}
}
环境:
public class Content {
private Strategy strategy;
public Content(String userType){
if(userType=="user"){
this.strategy= new UserStrategy();
}
if(userType=="vip"){
this.strategy= new VipUserStrategy();
}
}
/**
* 策略方法
*/
public void contextInterface(Double price){
strategy.strategyPrice(price);
}
}
使用时需要:
new Content(“vip”).contextInterface(19.88);
new Content(“user”).contextInterface(19.88);
还没有评论,来说两句吧...