实现一个简单的文本处理系统。
在这个系统中,我们将定义不同类型的文本处理策略,比如大小写转换、添加前缀后缀等,并使用工厂模式来管理这些策略。
1 定义一个枚举来标识不同的文本处理类型
public enum TextProcessTypeEnum {
UPPER_CASE,
LOWER_CASE,
PREFIX_SUFFIX
// 可以继续添加更多的文本处理类型
}
2 定义一个策略接口,所有的文本处理策略都将实现这个接口
public interface TextProcessHandler {
public String process(String txt);
public TextProcessTypeEnum getHandlerType();
}
3 实现几个具体的策略类
import org.springframework.stereotype.Service;
@Service
public class UpperCaseHandler implements TextProcessHandler {
@Override
public String process(String txt) {
return txt.toUpperCase();
}
@Override
public TextProcessTypeEnum getHandlerType() {
return TextProcessTypeEnum.UPPER_CASE;
}
}
@Service
public class LowerCaseHandler implements TextProcessHandler {
@Override
public String process(String txt) {
return txt.toLowerCase();
}
@Override
public TextProcessTypeEnum getHandlerType() {
return TextProcessTypeEnum.LOWER_CASE;
}
}
@Service
@NoArgsConstructor
public class PrefixSuffixHandler implements TextProcessHandler {
@Value("start--")
private String prefix;
@Value("--end")
private String suffix;
public PrefixSuffixHandler(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
@Override
public String process(String txt) {
return prefix +txt+ suffix;
}
@Override
public TextProcessTypeEnum getHandlerType() {
return TextProcessTypeEnum.PREFIX_SUFFIX;
}
}
4 创建一个工厂类来管理这些策略
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class TextProcessHandlerFactory implements InitializingBean {
@Autowired
private List<TextProcessHandler> textProcessHandlerList;
private final Map<TextProcessTypeEnum, TextProcessHandler> handlerMap =new HashMap<>();
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("textProcessHandlerList = " + textProcessHandlerList);
for (TextProcessHandler handler : textProcessHandlerList) {
handlerMap.put(handler.getHandlerType(), handler);
}
System.out.println("handlerMap = " + handlerMap);
}
public TextProcessHandler getHandler(TextProcessTypeEnum typeEnum)
{
return handlerMap.get(typeEnum);
}
}
5 使用这个工厂来获取相应的处理器,并处理文本
@SpringBootTest
class DemoMvnTest1ApplicationTests {
@Autowired
private TextProcessHandlerFactory factory;
@Test
void contextLoads() {
TextProcessHandler handler = factory.getHandler(TextProcessTypeEnum.UPPER_CASE);
System.out.println(handler.process("hello world"));
System.out.println();
handler = factory.getHandler(TextProcessTypeEnum.LOWER_CASE);
System.out.println(handler.process("HELLO WORLD"));
System.out.println();
handler = factory.getHandler(TextProcessTypeEnum.PREFIX_SUFFIX);
System.out.println(handler.process("hello world"));
}
}