Map<String, Consumer<String>>
은 명령을 작업에 연결하는 작업을 수행 할 수 있습니다.
GOF 공장 및 DP 명령이 아닙니다.
그러나 이것은 공장 및 명령 패턴의 공정하고 간단한 구현입니다.
그래서 고려해야합니다.
Map<String, Consumer<String>> actionsByCommand = new HashMap<>();
actionsByCommand.put("new train", command->{
command = command.replace("new train ", "");
Train t = new Train();
t.setCode(command);
ServiceProvider.getTrainService().saveOrUpdate(t);
responeHandler("train " + command + " created");
});
actionsByCommand.put("delete train", command->{
command = command.replace("delete train ", "");
...
});
// and so for...
당신은 또한 당신이지도에 넣어 필요가 없습니다 무효 명령에 대한 특별한 조치 만들 수 있습니다,
Consumer<String> invalidCommandAction = (command-> System.out.println("Invalid command. Here are the accepted commands..."));
이 테스트 용이성과 행동 클래스의 유지 보수성을 향상시키기 위해 당신이 할 수 그들을 다른 클래스로 옮기십시오.
public class NewTrainAction implements Consumer<String>{
public void accept(String command){
command = command.replace("new train ", "");
Train t = new Train();
t.setCode(command);
ServiceProvider.getTrainService().saveOrUpdate(t);
responeHandler("train " + command + " created");
}
}
과 같은 방법으로 정의 된 다른 작업
:
NewTrainAction
와
Map<String, Consumer<String>> actionsByCommand = new HashMap<>();
actionsByCommand.put("new train", new NewTrainCommand());
actionsByCommand.put("delete train", new DeleteTrainCommand());
는 다음과 같이 정의했다.
그럼 당신은이 방법을 사용할 수 있습니다
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String command = scanner.nextLine();
Consumer<String> action = actionsByCommand.getOrDefault(command, invalidCommandAction);
action.accept(command);
}
멋져 보이지만 실제로 호출 될 때마다 내 코드가 TrainCommandFactory에서 새로운 명령 인스턴스를 생성해야합니까? 또한'Singleton'' Composite'로 정확히 무엇을 의미합니까? 합성물은 내가 맞으면 객체의 나무와 같습니다. 그리고 싱글 톤은 오직 하나의 인스턴스 만 가질 수 있습니다. 그 2 개를 어떻게 연결시켜 주시겠습니까? – klokklok
Composite Singleton Factory에 대한 내 대답을 편집했습니다. 매번 명령 인스턴스를 생성하고 싶지 않으면'TrainCommand' 싱글 톤을 만들고'fromString'이 호출 될 때마다 팩토리를 반환하도록 할 수 있습니다. 하지만 String 인자를 받아들이려면'execute'를 바꿔야합니다. – daniu
고마워요. 저는 당신과 Martin Frank의 답변을 조합하여 사용했습니다! – klokklok