命令模式1
import java.util.ArrayList;
import java.util.List;
public class DeadFish {
/**
* i - increment
* d - decrement
* s - square
* o - output
*
* @param data
* @return
*/
public static int[] parse(String data) {
List<Integer> output = new ArrayList<>();
int counter = 0;
CommandFactory commandFactory = new CommandFactory(output);
for (char code: data.toCharArray()) {
Command command = commandFactory.getCommand(code);
counter = command.execute(counter);
}
return output.stream().mapToInt(i -> i).toArray();
}
}
class CommandFactory {
private final List<Integer> output;
public CommandFactory(List<Integer> output) {
this.output = output;
}
Command getCommand(char code) {
switch (code) {
case 'i': return new IncrementCommand();
case 'd': return new DecrementCommand();
case 's': return new SquareCommand();
case 'o': return new OutputCommand(output);
}
throw new RuntimeException("error");
}
}
interface Command {
int execute(int data);
}
class IncrementCommand implements Command {
@Override
public int execute(int data) {
return data+1;
}
}
class DecrementCommand implements Command {
@Override
public int execute(int data) {
return data-1;
}
}
class SquareCommand implements Command {
@Override
public int execute(int data) {
return data*data;
}
}
class OutputCommand implements Command {
private final List<Integer> output;
public OutputCommand(List<Integer> output) {
this.output = output;
}
@Override
public int execute(int data) {
output.add(data);
return data;
}
}
本文来自博客园,作者:ukyo--BlackJesus,转载请注明原文链接:https://www.cnblogs.com/ukzq/p/16694677.html