策略模式类似面向接口编程。即先创建一个接口,该接口是所有算法的基类,然后让其他算法类实现该接口。这样,不同的算法或者策略就可以有不同的实现。
简介
是定义一系列的算法,把每一个算法封装起来,使它们可相互替换。策略模式可以使算法的变化独立于使用它的客户,属于行为型模式
代码如下:
- 策略接口
/**
* @des 折扣活动的策略
*/
public interface DiscountActivityStrategy {
// 打折
void discount();
// 赠送礼品
void giveGifts();
}
2.策略实现
/**
* @des 新用户折扣活动的策略
*/
public class NewPersonDiscountActivityStrategyImpl implements DiscountActivityStrategy {
@Override
public void discount() {
Log.e("活动:","新用户--->"+"6折");
}
@Override
public void giveGifts() {
Log.e("活动:","新用户--->"+"汽车");
}
}
/**
* @des 普通用户折扣活动的策略
*/
public class PersonDiscountActivityStrategyImpl implements DiscountActivityStrategy {
@Override
public void discount() {
Log.e("活动:","普通用户--->"+"8折");
}
@Override
public void giveGifts() {
Log.e("活动:","普通用户--->"+"送个锤子");
}
}
/**
* @des Vip折扣活动的策略
*/
public class VipDiscountActivityStrategyImpl implements DiscountActivityStrategy {
@Override
public void discount() {
Log.e("活动:","Vip用户--->"+"五折");
}
@Override
public void giveGifts() {
Log.e("活动:","Vip用户--->"+"送法拉利");
}
}
3.策略环境
/**
* @des
*/
public class DiscountActivityStrategyContext {
private DiscountActivityStrategy strategy;
public void setStrategy(DiscountActivityStrategy strategy) {
this.strategy = strategy;
}
public DiscountActivityStrategy getStrategy() {
return strategy;
}
public void discount() {
if (strategy==null)return;
strategy.discount();
}
public void giveGifts() {
if (strategy==null)return;
strategy.giveGifts();
}
}
4.调用
class MainActivity : AppCompatActivity(), View.OnClickListener {
var discountActivityStrategyContext: DiscountActivityStrategyContext = DiscountActivityStrategyContext()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
binding.onClick = this
}
override fun onClick(v: View?) {
when (v!!.id) {
R.id.bt_do -> {
var personUser = VipDiscountActivityStrategyImpl()
discountActivityStrategyContext.strategy = personUser;
}
R.id.bt_new_do -> {
var newUser = NewPersonDiscountActivityStrategyImpl()
discountActivityStrategyContext.strategy = newUser;
}
R.id.bt_vip_do -> {
var vipUser = PersonDiscountActivityStrategyImpl()
discountActivityStrategyContext.strategy = vipUser;
}
}
discountActivityStrategyContext.discount()
discountActivityStrategyContext.giveGifts()
}
}