策略设计模式

策略模式(Strategy Pattern)是一种行为型设计模式,它定义了一系列算法或行为,并将每个算法封装到独立的类中,使得它们可以相互替换,而不影响客户端的使用。策略模式让算法的变化独立于使用算法的客户端。

策略模式主要包含以下几个角色:

  1. 策略接口(Strategy):定义了算法或行为的统一接口,所有具体策略类都实现了这个接口。
  2. 具体策略(ConcreteStrategy):实现了策略接口,封装了具体的算法或行为。
  3. 上下文(Context):持有一个策略对象,它将客户端的请求委派给策略对象执行。上下文可以根据需要动态地切换策略。

策略模式允许在运行时动态选择算法,使得客户端代码可以根据需求选择不同的策略,而不需要修改代码。

示例:
假设我们有一个电商系统,其中包含不同的折扣策略,例如:普通会员折扣、VIP会员折扣和满减折扣。我们可以使用策略模式来实现这些折扣策略。

// 策略接口:折扣策略
interface DiscountStrategy {
    double applyDiscount(double originalPrice);
}

// 具体策略:普通会员折扣
class RegularMemberDiscount implements DiscountStrategy {
    @Override
    public double applyDiscount(double originalPrice) {
        return originalPrice * 0.9; // 9折优惠
    }
}

// 具体策略:VIP会员折扣
class VipMemberDiscount implements DiscountStrategy {
    @Override
    public double applyDiscount(double originalPrice) {
        return originalPrice * 0.8; // 8折优惠
    }
}

// 具体策略:满减折扣
class FullReductionDiscount implements DiscountStrategy {
    @Override
    public double applyDiscount(double originalPrice) {
        if (originalPrice >= 200) {
            return originalPrice - 50; // 满减优惠,满200减50
        } else {
            return originalPrice;
        }
    }
}

// 上下文:电商商品
class Product {
    private String name;
    private double price;
    private DiscountStrategy discountStrategy;

    public Product(String name, double price, DiscountStrategy discountStrategy) {
        this.name = name;
        this.price = price;
        this.discountStrategy = discountStrategy;
    }

    public double getPrice() {
        return discountStrategy.applyDiscount(price);
    }

    public void setDiscountStrategy(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Product product1 = new Product("商品1", 100, new RegularMemberDiscount());
        Product product2 = new Product("商品2", 300, new VipMemberDiscount());

        System.out.println("商品1的价格:" + product1.getPrice()); // 输出:商品1的价格:90.0
        System.out.println("商品2的价格:" + product2.getPrice()); // 输出:商品2的价格:240.0

        // 动态切换策略
        product2.setDiscountStrategy(new FullReductionDiscount());
        System.out.println("商品2的价格(满减后):" + product2.getPrice()); // 输出:商品2的价格(满减后):250.0
    }
}

在上面的示例中,我们定义了一个折扣策略接口DiscountStrategy和三个具体策略类RegularMemberDiscountVipMemberDiscountFullReductionDiscount。然后,我们有一个电商商品类Product,其中包含了一个折扣策略对象。客户端代码可以根据需要创建不同的商品对象,并动态切换折扣策略。这样,客户端代码不需要关心具体的折扣计算方式,只需要通过上下文对象来应用不同的策略即可。

通过策略模式,我们可以轻松地添加新的折扣策略,而不需要修改现有的代码。同时,客户端代码可以动态地切换策略,实现了算法的灵活性和可扩展性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值