[Design Pattern] Verhaltensmuster: Command


Thomas Darimont

Premium-User
Hallo,

dieser Beitrag erklärt das Verhaltensmuster: Command

Java:
package de.tutorials.design.patterns.behavioral;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CommandPatternExample {

	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder("HELLO WORLD");
		List<UndoableCommand> commands = Arrays.<UndoableCommand>asList(new AppendString(sb, "AA"),new AppendString(sb, "BB"),new InsertString(sb, "XX",2));
		for(Command command : commands){
			command.execute();
			System.out.println(sb);
		}
		
		System.out.println("####");
		
		Collections.reverse(commands);
		for(UndoableCommand command : commands){
			command.undo();
			System.out.println(sb);
		}
	}

	static interface Command {
		void execute();
	}
	
	static interface UndoableCommand extends Command{
		void undo();
	}

	static abstract class StringManuipulationCommand implements UndoableCommand {

		final StringBuilder context;

		public StringManuipulationCommand(StringBuilder context) {
			this.context = context;
		}
	}

	static class AppendString extends StringManuipulationCommand {
		private String s;

		public AppendString(StringBuilder context, String s) {
			super(context);
			this.s = s;
		}

		@Override
		public void execute() {
			context.append(s);
		}
		
		@Override
		public void undo() {
			context.delete(context.length()-s.length(),context.length());
		}
	}
	
	static class InsertString extends StringManuipulationCommand {
		private String s;
		private int pos;

		public InsertString(StringBuilder context, String s, int pos) {
			super(context);
			this.s = s;
			this.pos = pos;
		}

		@Override
		public void execute() {
			context.insert(pos, s);
		}
		
		@Override
		public void undo() {
			context.delete(pos, pos+s.length());
		}
	}
}
Ausgabe:

Code:
HELLO WORLDAA
HELLO WORLDAABB
HEXXLLO WORLDAABB
####
HELLO WORLDAABB
HELLO WORLDAA
HELLO WORLD
Gruß Tom