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);

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值