Tianyi's Blog Tianyi's Blog
首页
  • 计算机网络
  • 操作系统
  • 计算机科学
  • Nginx
  • Vue框架
  • 环境配置
  • Java
  • JVM
  • Spring框架
  • Redis
  • MySQL
  • RabbitMQ
  • Kafka
  • Mirror Sites
  • Dev Tools
  • Docker
  • Jenkins
  • Scripts
  • Windows
  • 科学上网
  • 旅行
  • 网站日记
  • 软件
  • 电子产品
  • 杂野
  • 分类
  • 友情链接
GitHub (opens new window)

Tianyi

一直向前,永不停止
首页
  • 计算机网络
  • 操作系统
  • 计算机科学
  • Nginx
  • Vue框架
  • 环境配置
  • Java
  • JVM
  • Spring框架
  • Redis
  • MySQL
  • RabbitMQ
  • Kafka
  • Mirror Sites
  • Dev Tools
  • Docker
  • Jenkins
  • Scripts
  • Windows
  • 科学上网
  • 旅行
  • 网站日记
  • 软件
  • 电子产品
  • 杂野
  • 分类
  • 友情链接
GitHub (opens new window)
  • Java

    • web基础
    • 策略模式
      • Demo
        • 创建项目
        • 贴一下代码
    • Java基础语法
    • JavaWeb-Base
    • Optional处理空指针,这几招你会了吗?
    • 并发编程的艺术
    • 并发编程工具
    • 一个简单的 web 服务器实例
    • 小笔记-线程池
    • 小笔记-JUC入门
  • Golang

  • JVM的奇妙世界

  • Spring

  • Spring增强封装

  • Redis

  • MySQL

  • RabbitMQ

  • Kafka

  • 分享

  • 后端
  • Java
tianyi
2023-10-07
目录

策略模式

# 通过autowired实现策略模式

在工作中见到同事通过这种方法实现了一个区分云端与本地版场景也是使用这种设计模式。学习一下

参考 https://blog.csdn.net/puhaiyang/article/details/86697359

# Demo

# 创建项目

创建一个spring Boot项目

snipMate_2023-10-06_22-58-01.png

注意这里不适用Spring Boot 3 版本

  • Spring Boot 3版本于2022年11月24日发布,它是Spring Boot的下一个大版本,基于Spring Framework 6.0,而且要求Java最低版本为Java17。

# 贴一下代码

结构如下

@Component
public class MyContext {
    /**
     * 使用线程安全的ConcurrentHashMap存储所有实现Strategy接口的Bean
     * key:beanName
     * value:实现Strategy接口Bean
     */
    private final Map<String, TalkService> strategyMap = new ConcurrentHashMap<>();

    @Autowired
    public MyContext(Map<String, TalkService> strategyMap) {
        this.strategyMap.clear();
        this.strategyMap.putAll(strategyMap);
        strategyMap.forEach((k,v) -> {
            System.out.println(k);
            System.out.println(v.toString());
        });
    }

    public Object talk(String memberLevel) {
        if (!StringUtils.isEmpty(memberLevel)) {
            return strategyMap.get(memberLevel);
        }
        return null;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

打印出来

2023-10-07 00:49:57.440  INFO 25708 --- [           main] com.hello.MyApplication                  : No active profile set, falling back to 1 default profile: "default"
talkServiceStrategyContext
com.hello.Service.TalkServiceStrategyContext@15deb1dc
withGirlFriendTalkService
com.hello.Service.WithGirlFriendTalkService@6e9c413e
withSisterTalkService
com.hello.Service.WithSisterTalkService@57a4d5ee
2023-10-07 00:49:57.735  INFO 25708 --- [           main] com.hello.MyApplication                  : Started MyApplication in 0.476 seconds (JVM running for 1.291)
1
2
3
4
5
6
7
8
完善页面 (opens new window)
web基础
Java基础语法

← web基础 Java基础语法→

最近更新
01
JDK
02-23
02
BadTasteCode && 优化
09-11
03
Gradle 实践操作指南及最佳实践
09-11
更多文章>
Theme by Vdoing | Copyright © 2021-2025 Tandy | 粤ICP备2023113440号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式