策(ce)略模(mo)式的應用
策略模式的應用,我們以一個配置字典來說一下這個問題;首先這個字典用來管理若干個配置,每個配置項都有key和value,key是字符串,value是某種類型;我們通過一個ConfigServiceStrategy接口來規定配置的操作行為,通過ConfigServiceContext來表示一個配置上下文,通過這個對象可以寫配置,讀配置等;通過接口隔離原則,像上下文里傳遞的參數是一個抽象的接口ConfigServiceStrategy,而(er)具體的實(shi)現(xian)就是配置(zhi)持(chi)久化的方式,如(ru)內存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);
}
}
測試用例
可(ke)以通過(guo)bean的方式進(jin)行注(zhu)入,這里只是(shi)測(ce)試
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"));
}