Behavioral Patterns

Observer Pattern

Concepts

Design

Observable

public interface Observable<T extends Observer> {
	void register(T observer);
	void unregister(T observer);
	void notify()
	List<Observer> getAllObservers();
}

What is an Observer?

Observer Summary

Strategy Pattern

Concepts

Design

Collections.sort(people, new Comparator<Person>() {
		@Override
		public int compare(Person o1, Person o2) {
				if(o1.getAge() > o2.getAge()){
						return 1;
				}
				if (o1.getAge() < o2.getAge()) {
						return -1;
				}
				return 0;
		}
});

Collections.sort uses the Strategy pattern. The method expects a strategy to be passed as an argument. This allows the client to decide by which strategy the sort method will execute

Strategy Summary

Template Pattern

// degree of 1
public static Integer[] getRange(int start) {
    return getRange(0, start, 1);
}

// degree of 2
public static Integer[] getRange(int start, int stop) {
    return getRange(start, stop, 1);
}

// degree of 3; template method
public static Integer[] getRange(int start, int stop, int step) {
    List<Integer> list = new ArrayList<>();
    for(int i = start; i<stop; i+=step) {
        list.add(i);
    }
    return list.toArray(new Integer[list.size()]);
}

Command Pattern

Command Pattern

You’ll see command being used a lot when you need to have multiple undo operations, where a stack of the recently executed commands are maintained. To implement the undo, all you need to do is get the last Command in the stack and execute it’s undo() method.

You’ll also find Command useful for wizards, progress bars, GUI buttons and menu actions, and other transactional behavior.