策略模式

介绍

**定义:**通过定义一系列算法并封装每个算法的方式使其可以独立于客户端变化, 并使它们之间可以进行自由的相互替换.

UML

示例

java 复制代码
package com.sumlv.demo;

import com.sumlv.demo.entity.Order;
import com.sumlv.demo.enumeration.PaymentType;
import com.sumlv.demo.factory.PaymentStrategyFactory;
import com.sumlv.demo.strategy.PaymentStrategy;

import java.math.BigDecimal;

public class Main {

    public static void main(String[] args) {
        Order order = new Order(
                1L,
                2L,
                3L,
                new BigDecimal("100.00"),
                PaymentType.ALIPAY
        );

        PaymentStrategy paymentStrategy = PaymentStrategyFactory.getPaymentStrategy(order.getPaymentType());
        paymentStrategy.handle(order);
    }

}
java 复制代码
package com.sumlv.demo.factory;

import com.sumlv.demo.enumeration.PaymentType;
import com.sumlv.demo.strategy.AliPayPaymentStrategy;
import com.sumlv.demo.strategy.PaymentStrategy;
import com.sumlv.demo.strategy.WeChartPaymentStrategy;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付策略工厂
 *
 * @Auther: yuzhuo.song
 * @Date: 2026-03-21
 */
public class PaymentStrategyFactory {

    private static final Map<PaymentType, PaymentStrategy> STRATEGY_MAP = new HashMap<>();

    static {
        STRATEGY_MAP.put(PaymentType.WE_CHART, new WeChartPaymentStrategy());
        STRATEGY_MAP.put(PaymentType.ALIPAY, new AliPayPaymentStrategy());
    }

    public static PaymentStrategy getPaymentStrategy(PaymentType paymentType) {
        return STRATEGY_MAP.get(paymentType);
    }

}
java 复制代码
package com.sumlv.demo.strategy;

import com.sumlv.demo.entity.Order;

/**
 * 支付策略(抽象策略类)
 *
 * @Auther: yuzhuo.song
 * @Date: 2026-03-21
 */
public interface PaymentStrategy {

    void handle(Order order);

}
java 复制代码
package com.sumlv.demo.strategy;

import com.sumlv.demo.entity.Order;

/**
 * 微信支付策略(具体策略类)
 *
 * @Auther: yuzhuo.song
 * @Date: 2026-03-21
 */
public class WeChartPaymentStrategy implements PaymentStrategy {

    @Override
    public void handle(Order order) {
        // 此处省略微信支付具体逻辑
        System.out.println("使用微信支付:" + order);
    }

}
java 复制代码
package com.sumlv.demo.strategy;

import com.sumlv.demo.entity.Order;

/**
 * 支付宝支付策略(具体策略类)
 *
 * @Auther: yuzhuo.song
 * @Date: 2026-03-21
 */
public class AliPayPaymentStrategy implements PaymentStrategy {


    @Override
    public void handle(Order order) {
        // 此处省略支付宝支付具体逻辑
        System.out.println("使用支付宝支付:" + order);
    }

}
java 复制代码
package com.sumlv.demo.entity;

import com.sumlv.demo.enumeration.PaymentType;

import java.math.BigDecimal;

/**
 * 订单
 *
 * @Auther: yuzhuo.song
 * @Date: 2026-03-21
 */
public class Order {

    private Long id;

    private Long userId;

    private Long productId;

    private BigDecimal price;

    private PaymentType paymentType;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Long getProductId() {
        return productId;
    }

    public void setProductId(Long productId) {
        this.productId = productId;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public PaymentType getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(PaymentType paymentType) {
        this.paymentType = paymentType;
    }

    public Order(Long id, Long userId, Long productId, BigDecimal price, PaymentType paymentType) {
        this.id = id;
        this.userId = userId;
        this.productId = productId;
        this.price = price;
        this.paymentType = paymentType;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id='" + id + '\'' +
                ", userId='" + userId + '\'' +
                ", productId='" + productId + '\'' +
                ", price=" + price +
                ", paymentType=" + paymentType +
                '}';
    }

}
java 复制代码
package com.sumlv.demo.enumeration;

/**
 * 支付类型
 *
 * @Auther: yuzhuo.song
 * @Date: 2026-03-21
 */
public enum PaymentType {

    WE_CHART,

    ALIPAY;

}

总结

使用场景

  1. 当系统中存在多重if else逻辑时, 可以使用策略模式替换;

  2. 当某一功能可以有多种不同实现时, 可以使用策略模式封装其每一种实现;

  3. 当我们希望隐藏某些业务的实现逻辑时, 可以使用策略模式对该算法进行封装.

优点:

1.多个策略之间可以自由切换且易于拓展;

  1. 可以替代代码中的多重if else, 体现面向对象的编程思想.

缺点:

  1. 客户端必须知道所有的策略类并自行决定使用哪个类;

  2. 如果算法过多则会产生非常多的策略类, 占用系统内存.

相关推荐
Chester_19994 小时前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
EXI-小洲5 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
会周易的程序员5 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导6 小时前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan6 小时前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_695251496 小时前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
2601_961901706 小时前
SpringBoot使用Nacos进行application.yml配置管理
java·spring boot·spring
何以解忧,唯有..7 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
大衛說7 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
QQ_21696290967 小时前
【源码编号:project79475】SpringBoot校内二手交易平台:商品发布、分类检索、留言交流、订单管理全流程实战
java·spring boot·后端