實現一個簡單的文本處理系統。
在這個系統中,我們將定義不同類型的文本處理策略,比如大小寫轉換、添加前綴后綴等,并使用工廠模式來管理這些策略。
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 {@Overridepublic String process(String txt) {return txt.toUpperCase();}@Overridepublic TextProcessTypeEnum getHandlerType() {return TextProcessTypeEnum.UPPER_CASE;}
}@Service
public class LowerCaseHandler implements TextProcessHandler {@Overridepublic String process(String txt) {return txt.toLowerCase();}@Overridepublic 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;}@Overridepublic String process(String txt) {return prefix +txt+ suffix;}@Overridepublic 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 {@Autowiredprivate List<TextProcessHandler> textProcessHandlerList;private final Map<TextProcessTypeEnum, TextProcessHandler> handlerMap =new HashMap<>();@Overridepublic 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 {@Autowiredprivate TextProcessHandlerFactory factory;@Testvoid 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"));}}