策略设计模式

策略设计模式(Strategy Pattern)是一种行为型设计模式,它定义了一系列算法,并将每个算法封装起来,使得它们可以互相替换,且算法的变化不会影响使用算法的客户。这个模式使得算法可以在不影响客户端的情况下发生变化。

关键角色

  1. 抽象策略(Strategy):定义所有支持的算法的公共接口。
  2. 具体策略(Concrete Strategy):实现具体的算法。
  3. 上下文(Context):维护一个策略类的引用,用于调用具体的算法。

示例

以下以登录为示例,演示策略设计模式。

java 复制代码
package com.example.study.pattern;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;;

@Slf4j
@SpringBootTest
class ApplicationTests {

    @Test
    void contextLoads() {

        LoginStrategy usernamePasswordLoginStrategy = new UsernamePasswordLogin("lili", "123456");
        LoginContext lili = new LoginContext(usernamePasswordLoginStrategy);
        lili.login();

        LoginStrategy verificationCodeLoginStrategy = new VerificationCodeLogin("18655141030", "225433");
        LoginContext tom = new LoginContext(verificationCodeLoginStrategy);
        tom.login();
    }

    interface LoginStrategy {
        void login();
    }

    class UsernamePasswordLogin implements LoginStrategy {

        private String username;
        private String password;

        public UsernamePasswordLogin(String username, String password) {
            this.username = username;
            this.password = password;
        }

        @Override
        public void login() {
            log.info("用户名密码登录, 用户:{}", this.username);
        }
    }

    class VerificationCodeLogin implements LoginStrategy {

        private String phone;
        private String verificationCode;

        public VerificationCodeLogin(String phone, String verificationCode) {
            this.phone = phone;
            this.verificationCode = verificationCode;
        }

        @Override
        public void login() {
            log.info("手机验证码登录, 用户:{}", this.phone);
        }
    }

    class LoginContext {
        private LoginStrategy loginStrategy;

        public LoginContext(LoginStrategy loginStrategy) {
            this.loginStrategy = loginStrategy;
        }

        public void login() {
            loginStrategy.login();
        }
    }

}

运行结果

策略模式的优点

  1. 易于切换算法:可以在运行时切换不同的算法。
  2. 避免使用条件判断:通过使用策略类代替条件语句(如 if-else 或 switch-case)。
  3. 开放封闭原则:新增算法时只需增加新的策略类,不需要修改现有代码。

适用场景

  1. 多个类只区别在表现行为不同:可以使用策略模式来动态选择具体的行为。
  2. 需要在不同情况下使用不同的算法:如不同的排序算法、不同的加密算法等。
  3. 避免使用条件判断语句:可以将条件判断语句替换为策略模式中的策略类。

策略设计模式通过将算法的实现与使用分离,提高了代码的灵活性和可维护性,在各种需要灵活切换算法的场景中得到了广泛应用。

相关推荐
七月丶5 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞5 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼5 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室1 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式