Skip to content


Observer pattern

Observer is a software design pattern, that is used when some objects create events and other objects should be notified when these events occur.

The main idea is that we have two types of instances: one that produces events and one that consumes them. Events producer must have three methods:

  1. addObserver(Observer observer)
  2. removeObserver(Observer observer)
  3. notifyObservers(…)

The first two methods are used to add and delete observers from a collection. The third method must iterate that collection and call notify(…) method of the Observer instance.

Java has its own Observer interface and Observable class, but sometimes we don’t want to extend from a class, or we want to adjust the API, you can create your own interfaces, as I’ve done in the following example:

Read More →

Strategy pattern

With this post I’m starting series of articles dedicated to GoF design patterns. GoF stands for Gang of Four – four authors that wrote a famous book about design patterns.

So the first pattern I want to describe is Strategy. It allows to choose the behaviour of instances at runtime by defining appropriate strategy.

Let’s see an example. Supposing we have a class Order, which has getTotal() method, that returns total cost of Items in this order:


public int getTotal() {
	int total = 0;
	for (Item item : items) {
		total += item.getPrice();
	return total;


Very simple, isn’t it? But what if we want to change the price depending on some circumstances? That’s where we can use the Strategy pattern. Click read more to see full example.

Read More →