Skip to content

Instantly share code, notes, and snippets.

@TheSecretSquad
Last active August 29, 2015 14:23
Show Gist options
  • Save TheSecretSquad/b1889441a90b71a91a66 to your computer and use it in GitHub Desktop.
Save TheSecretSquad/b1889441a90b71a91a66 to your computer and use it in GitHub Desktop.
// Original implementation
public class ConsoleCommandSource implements CommandSource {
private final Console console;
private final TextParser textParser;
public ConsoleCommandSource(final Console console, final TextParser textParser) {
this.textParser = textParser;
this.console = console;
}
public void parseTo(final CommandReceiver commandReceiver) {
console.parseInputToReceiver(textParser, commandReceiver);
}
}
public class ExampleConsole implements Console {
public void parseInputToReceiver(final TextParser textParser, final CommandReceiver commandReceiver) {
while(/* Get user input */) {
// Passing same commandReceiver object each time
textParser.parseInputTo(stringInput, commandReceiver);
}
}
}
// Changed implementation with factory
public class ConsoleCommandSource implements CommandSource {
private final Console console;
private final TextParserFactory textParserFactory;
public ConsoleCommandSource(final Console console, final TextParserFactory textParserFactory) {
this.textParserFactory = textParserFactory;
this.console = console;
}
public void parseTo(final CommandReceiver commandReceiver) {
// Create the TextParser with the commandReceiver
console.sendInputTo(textParserFactory.create(commandReceiver));
}
}
// ExampleConsole becomes
public class ExampleConsole implements Console {
public void parseInputToReceiver(final TextParser textParser) {
while(/* Get user input */) {
textParser.parseInputTo(stringInput);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment