新增不同动物叫声的适配器AnimalCallCryService
package com.example.jvm.demo.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* 不同动物叫声的适配器
*
* @author fangxc
* @version V1.0.0
* @date 2022/2/10 14:28
*/
@Service
public class AnimalCallCryService {
@Autowired
private AnimalTypeCryService animalTypeCryService;
private Map> animalTypeServiceMap = new ConcurrentHashMap<>();
@PostConstruct
private void animalCallInit() {
animalTypeServiceMap.put('dog', animalType -> animalTypeCryService.dogCry(animalType));
animalTypeServiceMap.put('cat', animalType -> animalTypeCryService.catCry(animalType));
}
public String getResult(String animalType) {
Function result = animalTypeServiceMap.get(animalType);
if (result != null) {
return result.apply(animalType);
}
return '没有匹配的动物叫声!';
}
}
新增一个不同动物的叫声统一实现类AnimalTypeCryService
package com.example.jvm.demo.service.impl;
import org.springframework.stereotype.Service;
/**
* 不同动物的叫声统一实现类
*
* @author fangxc
* @version V1.0.0
* @date 2022/2/10 14:25
*/
@Service
public class AnimalTypeCryService {
public String dogCry(String animalType) {
return '狗汪汪叫!';
}
public String catCry(String animalType) {
return '猫喵喵叫!';
}
}
新增单元测试,查看效果
@Autowired
private AnimalCallCryService animalCallCryService;
@Test
public void animalAdaptTest2() throws Exception {
System.out.println(animalCallCryService.getResult('dog'));
System.out.println(animalCallCryService.getResult('cat'));
System.out.println(animalCallCryService.getResult('test'));
}
用这种方式,我个人建议是把同一类行为进行统一封装,而不是像策略模式那样对同一类对象进行封装。
本篇结合下Java8的函数式接口,换一种思路实现类似的效果
文章为作者独立观点,不代表股票交易接口观点