策略设计模式

策略设计模式(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. 避免使用条件判断语句:可以将条件判断语句替换为策略模式中的策略类。

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

相关推荐
渣渣_Maxz15 小时前
使用 antlr 打造 Android 动态逻辑判断能力
android·设计模式
码农颜18 小时前
java 设计模式_行为型_19命令模式
java·设计模式·命令模式
蔡蓝1 天前
设计模式-迭代器模式
设计模式·迭代器模式
梦想画家1 天前
数据管道架构设计指南:5大模式与最佳实践
设计模式·数据工程·数据编排
牛奶咖啡131 天前
学习设计模式《十三》——迭代器模式
设计模式·迭代器模式·内部迭代器和外部迭代器·带迭代策略的迭代器·双向迭代器·迭代器模式的优点·何时选用迭代器模式
哆啦A梦的口袋呀1 天前
设计模式汇总
python·设计模式
在未来等你2 天前
设计模式精讲 Day 1:单例模式(Singleton Pattern)
java·设计模式·面向对象·软件架构
不会编程的小江江2 天前
【设计模式】单例模式
单例模式·设计模式
哆啦A梦的口袋呀2 天前
基于Python学习《Head First设计模式》第十一章 代理模式
学习·设计模式·代理模式
Dave_Young2 天前
上位机开发中的设计模式(3):装饰器模式
设计模式·装饰器模式