策略模式

介绍

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

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. 如果算法过多则会产生非常多的策略类, 占用系统内存.

相关推荐
摇滚侠11 分钟前
VMvare 虚拟机 Oracle19c 安装步骤,远程连接 Oracle19c,百度网盘安装包
java·oracle
梁萌14 分钟前
idea报错找不到XX包的解决方法
java·intellij-idea·启动报错·缺少包
Agent产品评测局21 分钟前
生产排期与MES/ERP系统打通,实操方法详解 —— 2026企业级智能体自动化选型与实战指南
java·运维·人工智能·ai·chatgpt·自动化
cen__y24 分钟前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
阿丰资源42 分钟前
基于Spring Boot的电影城管理系统(直接运行)
java·spring boot·后端
xingpanvip44 分钟前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
guygg881 小时前
基于遗传算法的双层规划模型求解MATLAB实现
开发语言·matlab
呱牛do it1 小时前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 8)
java
凯瑟琳.奥古斯特1 小时前
SQLAlchemy核心功能解析
开发语言·python·flask
卷Java1 小时前
GPTQ vs AWQ vs GGUF:模型量化工具横向测评
开发语言·windows·python