策略模式的应用

策略模式的应用,我们以一个配置字典来说一下这个问题;首先这个字典用来管理若干个配置,每个配置项都有key和value,key是字符串,value是某种类型;我们通过一个ConfigServiceStrategy接口来规定配置的操作行为,通过ConfigServiceContext来表示一个配置上下文,通过这个对象可以写配置,读配置等;通过接口隔离原则,像上下文里传递的参数是一个抽象的接口ConfigServiceStrategy,而具体的实现就是配置持久化的方式,如内存hash表,redis的hash存储等。

配置文件的策略接口

/**
 * 配置服务策略.
 *
 * @author lind
 * @date 2024/12/23 22:00
 * @since 1.0.0
 */
public interface ConfigServiceStrategy {

	/**
	 * 存储配置.
	 */
	<T> void put(Class<T> type, String key, T value);

	/**
	 * 获取配置.
	 * @param type
	 * @param key
	 * @return
	 * @param <T>
	 */
	<T> T get(Class<T> type, String key);

}

内存hash表实现策略

/**
 * 基于类型和key的字典存储.
 *
 * @author lind
 * @date 2024/12/23 14:22
 * @since 1.0.0
 */
public class DictionaryConfigService implements ConfigServiceStrategy {

	private Map<ConfigKey<?>, Object> configKeyObjectMap = new HashMap<>();

	@Override
	public <T> void put(Class<T> type, String key, T value) {
		configKeyObjectMap.put(ConfigKey.of(type, key), value);
	}

	@Override
	public <T> T get(Class<T> type, String key) {
		ConfigKey configKey = ConfigKey.of(type, key);

		return type.cast(configKeyObjectMap.get(configKey));
	}

}

配置文件的上下文

/**
 * 配置服务上下文
 *
 * @author lind
 * @date 2024/12/23 22:57
 * @since 1.0.0
 */
public class ConfigServiceContext implements ConfigServiceStrategy {

	private ConfigServiceStrategy configServiceStrategy;

	public ConfigServiceContext(ConfigServiceStrategy configServiceStrategy) {
		this.configServiceStrategy = configServiceStrategy;
	}

	/**
	 * 存储配置.
	 * @param type
	 * @param key
	 * @param value
	 */
	@Override
	public <T> void put(Class<T> type, String key, T value) {
		if (this.configServiceStrategy == null) {
			throw new IllegalStateException("未设置配置服务");
		}
		this.configServiceStrategy.put(type, key, value);
	}

	/**
	 * 获取配置.
	 * @param type
	 * @param key
	 * @return
	 */
	@Override
	public <T> T get(Class<T> type, String key) {
		if (this.configServiceStrategy == null) {
			throw new IllegalStateException("未设置配置服务");
		}
		return this.configServiceStrategy.get(type, key);
	}

}

测试用例

可以通过bean的方式进行注入,这里只是测试

public static void main(String[] args) {
    ConfigServiceContext configServiceContext = new ConfigServiceContext(new DictionaryConfigService());
    configServiceContext.put(String.class, "test", "test");
    System.out.println(configServiceContext.get(String.class, "test"));
}
posted @   张占岭  阅读(288)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· RFID实践——.NET IoT程序读取高频RFID卡/标签
历史上的今天:
2011-12-31 IE和火狐中模仿Click事件及提交到新窗口总结
点击右上角即可分享
微信分享提示