Scala Mashup Series: The Template Method in Java, Spring and Scala

Continuing the Scala Mashup Series, this post is about a quite important, often used, but also controversial pattern: The Template Method.

In general, there are great explanations of the pattern in Wikipedia and of course in Head First Design Patterns.

Criticism

A very good summary of the Template Method pattern especially in comparison to the Strategy pattern is on stackoverflow.com:

The Template pattern does compile-time algorithm selection by subclassing.
The Strategy pattern does run-time algorithm selection by containment.

Example

Imagine you want to arrange a dinner. The entire algorithm for arranging a dinner is predefined:

  1. Invite your guests
  2. Go shopping
  3. Clean your fridge to provide enough space
  4. Prepare the meal
  5. Server the meal
  6. Wash the dishes

Now, some parts of this algorithm (which in its entirety is called arrange) are fixed (invariant parts). Other parts are highly dependant on the meal you want to prepare (variant parts).
In Template Method, the algorithm itself is described in a public accessible method, eg. arrange(), which combines and calls the variant and invariant methods. The invariant methods are implemented in the abstract super class. The variant parts are implemented in the concrete classes, eg. BratwurstDinner, which implements the concrete way to do shopping for the BratwurstDinner, as well as the preparation of the Bratwurst itself.
The important part is the compile-time binding – the implementing, concrete classes cannot change their implementation during runtime.
This makes the Template Method almost ideal for framework creation, when you want to provide abstract algorithms with certain concrete implementations (think of abstract database layers, with an algorithm which cares for opening & establishing connections, handles exceptions and cleans up nicely after doing … the variant part, which is implemented in the concrete classes).

Here is the dinner example using the Template Method pattern

Here is the dinner example using the Strategy pattern

There are two clever blog posts, one about disadvantages of the Template Method pattern, and one mentioning a possible alternative in languages with first class functions like Scala.

Language comparison: Java, Scala, Spring

We will happily leave out the Java example, since it is just too obvious. In the Wikipedia article a sample is given, together with the class diagram it should be pretty obvious how Template Method is implemented in Java. The only thing to keep in mind is to set the super class abstract, as well as the variant methods – which are then implemented (using @Override) in the concrete classes.

Scala

In Scala there are is the intuitive way of implemeting the Template Method, analogous to Java:

abstract class DinnerEvent {

  def arrange: Unit = {
    makeGuestList
    doShopping
    cleanFridge
    prepareMeal
    serveMeal
    washDishes
  }

  def prepareMeal: Unit
  def doShopping: Unit

  def makeGuestList: Unit = {
    println("making guest list...")
  }

  def cleanFridge: Unit = {
    println("cleaning fridge...")
  }

  def serveMeal: Unit = {
    println("serving meal...")
  }

  def washDishes: Unit = {
    println("washing dishes...")
  }

}

trait TurkeyDinner {

  def doShopping: Unit =  {
    println("...buying turkey")
  }

  def prepareMeal: Unit =  {
    println("...preparing turkey")
  }

}

object TemplateMethod {

  def main(args:Array[String]) = {
    val dinner = new DinnerEvent with TurkeyDinner
    dinner.arrange
  }

}

However, in languages with first class functions, it is too tempting to use the Strategy pattern:

class DinnerEventWithStrategy(shoppingStrategy: => Unit, preparingStrategy: => Unit) {

  def arrange: Unit = {
    makeGuestList
    shoppingStrategy
    cleanFridge
    preparingStrategy
    serveMeal
    washDishes
  }

  def makeGuestList: Unit = {
    println("making guest list...")
  }

  def cleanFridge: Unit = {
    println("cleaning fridge...")
  }

  def serveMeal: Unit = {
    println("serving meal...")
  }

  def washDishes: Unit = {
    println("washing dishes...")
  }

}

object Closure {

  def turkeyShoppingStrategy: Unit = {
    println ("...shopping turkey strategy")
  }

  def turkeyPreparationStrategy:Unit = {
    println ("...preparing turkey strategy")
  }

  def main(args:Array[String]) = {
    val dinner = new DinnerEventWithStrategy(turkeyShoppingStrategy, turkeyPreparationStrategy)
    dinner.arrange
  }

}

So, you should choose wisely, both patterns definitely have their scope of application – just keep in mind that Strategy also uses composition over inheritance, which is always a good advise.

…and what about Spring?

This is interesting, Spring uses the Template Method a lot – and many think it is one of their greatest strengths.
But wait … the Template Method pattern? Not really. The Spring Framework templates in fact are not implementing the Template Method pattern, even if it feels this way.
Let’s examine a small usage example of Spring’s JdbcTemplate:

package com.commons.sample.dao;

import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

public class JdbcSimpleDao extends SimpleJdbcDaoSupport implements SimpleDao {

	final static String single	= "select id, name from test where id = ?";
	final static String list 	= "select id, name from test"; 

	public Simple getSimpleById(int id) {
		return getSimpleJdbcTemplate().queryForObject(single,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class), id);
	}

	public List<Simple> getSimples() {
		return getSimpleJdbcTemplate().query(list,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class));
	}

}

What is happening here? Even though the class extends SimpleJdbcDaoSupport, it would not have to.
The Method query(…) takes the SQL and a ParameterizedBeanPropertyRowMapper.newInstance(Simple.class), which defines a row mapper that creates an object of class Simple – this certainly describes a strategy. So, even the so-called Spring Templates actually uses the Strategy pattern.

Summary

The Template Method is a powerful pattern. Use it if you create a framework, since you can inject certain functionality in the implementing classes at compile time, which let the user of your framework extend it easily, but in a controlled and “traceable” way. For Java, it is a natural way to enable users of your classes to extends the functionality at certain points.
In languages with first-order functions (or closures), like Scala, it might feel more natural to use the Strategy pattern instead. However, keep in mind that the patterns are not completely identical.

Scala Mashup Series: Simple Factory, Factory Method and Abstract Factory

Up to now, I identified three different kinds of factory patterns, which are similar to each other.

Simple, but powerful: The Simple Factory

The simple factory in Java is implemented as a static method, which returns a object of a certain type. This object can be newly created or a singleton (in contrast to object creation with constructors, which create new objects always).

Advantages [taken from Effective Java (2nd Edition)]

  1. Factory methods have names
  2. Constructors differ only by signature. With factory methods, the method itself can describe the kind of object created.

  3. Factory methods decide what kind of objects are created
  4. With factory methods, newly created objects can be returned as well as singletons.

  5. Factory methods can return objects of any subtype
  6. Depending on the submitted arguments, the method can decide to return subtypes of the return type (see example below).

  7. Verbosity of creating parameterized type instances is reduced
  8. Redundant specification of the form Map map = new HashMap() is not necessary with factory methods, since the compiler is able to infer the type by type inference.

Disadvantages:

  1. Factory methods do not favor inheritance
  2. Returned (non-public) types of factory methods cannot be subclasses (if they have no public or protected constructors).

  3. Factory methods cannot be identified as creational methods as easy as constructors
  4. This can be leveled by using conventions, eg. valueOf, getInstance, of depending on the context.

public class Factory {

    public static Item createItem( Object decideUpon ) {

        int itemType = figureOutItemType( decideUpon );

        switch( itemType ) {
            case Constants.Type1:
                return new Type1();
            case Constants.Type2:
                return new Type2();
            // etc.
        }
    }
}

And now in Scala:

object Factory {

  def createItem( decideUpon:String ):Item = decideUpon match {
    case "type1" => new Item1Type
    case "type2" => new Item2Type
    case _ => error("Unknown option.")
  }

}

The real Factory Method

The Factory Method is used to create several concrete objects of one abstract class.
In contrast to the Simple Factory described above, the factory itself is subclassed, therefore a concrete factory which creates concrete classes can be created depending on the context.

public abstract class Factory {

    public abstract Item createItem();

}
public class Item1Factory extends Factory {

    public Item createItem() {
        return new Type1();
    }

}
public class Item2Factory extends Factory {

    public Item createItem() {
        return new Type2();
    }

}

In Scala, the code is almost the same, is might just be simplyfied by the use of pattern matching (not equal to the Java version).

trait Factory {  

  def create( decideUpon:String ): Item

}
object Item1Factory extends Factory {

  def create(): Item = instanceType match {
    case "type1" => new Type1Item
    case _ => error("Unknown option.")
  }

}

Last, not least: Abstract Factory

In short, an Abstract Factory is used to create families of related objects.
The creation methods inside the Abstract Factories are usually implemented as Factory Methods.

Posted in Patterns. Comments Off

Patters (cont’d): The Observer Pattern

Download Eclipse project

I implemented the Observer Pattern with a central registry which is synchronized and uses WeakHashMaps, thereby trying to omit memory leaks.

The Notification Manager:

package observer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class NotificationManager implements Observable {

	private Map<Integer, List<Observer>> observers = new WeakHashMap<Integer, List<Observer>>();

	private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	private final Lock read = readWriteLock.readLock();
	private final Lock write = readWriteLock.writeLock();

	public void notifyObservers(Object source, Object arg) {
		List<Observer> obs = null;
		read.lock();
		try {
			if (!observers.containsKey(source.hashCode())) {
				return;
			} else {
				obs = observers.get(source.hashCode());
			}
			for (Observer observer : obs) {
				observer.update(arg);
			}
		} finally {
			read.unlock();
		}
	}

	public void register(Object target, Observer observer) {
		List<Observer> obs = null;
		write.lock();
		try {
			if (!observers.containsKey(target.hashCode())) {
				obs = new ArrayList<Observer>();
			} else {
				obs = observers.get(target.hashCode());
			}
			if (!obs.contains(observer)) {
				obs.add(observer);
			}
			observers.put(target.hashCode(), obs);
		} finally {
			write.unlock();
		}
	}

	public void remove(Object target, Observer observer) {
		List<Observer> obs = null;
		write.lock();
		try {
			if (!observers.containsKey(target.hashCode())) {
				return;
			} else {
				obs = observers.get(target.hashCode());
			}
			if (!obs.contains(observer)) {
				return;
			}
			obs.remove(observer);
		} finally {
			write.unlock();
		}
	}

	public String toString() {
		return "#Observers: ".concat(String.valueOf(observers.entrySet().size()));
	}

}

The Observer interface:

package observer;

public interface Observer {

	public void update(Object arg);

}

The Observable interface implemented by the NotificationManager:

package observer;

public interface Observable {

	public void register(Object target, Observer observer);
	public void remove(Object target, Observer observer);

	public void notifyObservers(Object source, Object arg);

}

The unit test class extending AbstractDependencyInjectionSpringContextTests:

package observer;

import org.springframework.test.AbstractDependencyInjectionSpringContextTests;

public class ObserverTest extends AbstractDependencyInjectionSpringContextTests implements Observer {

	protected NotificationManager notificationmanager;

	public ObserverTest() {
		setPopulateProtectedVariables(true);
	}

	public ObserverTest(String s) {
		super(s);
		setPopulateProtectedVariables(true);
	}

	public void testNM() {
		ObservableObject oo = new ObservableObject();
		notificationmanager.register(oo, this);
		oo.notifyObs();
		notificationmanager.remove(oo, this);
		oo.notifyObs();
	}

	@Override
	protected String[] getConfigLocations() {
		return new String[]{"applicationContext-test.xml"};
	}

	public void update(Object arg) {
		System.out.println("called with " + arg);
	}

	private class ObservableObject {

		public void notifyObs() {
			notificationmanager.notifyObservers(this, "bla");
		}

	}

}

The config, the notificationmanager is injected into the protected variable in the junit test:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

	<bean id="notificationmanager" class="observer.NotificationManager"/>

</beans>

Patterns with Spring

Download Eclipse project

There are several articles about Patterns with Spring in “Enterprise” context, ie. on the server side and simulating more or less typical JEE Patterns. These are important, however, Spring has its use in small, batch and client side apps as well.
Therefore, it makes sense to recall old school Design Patterns, which can be used independently of the programming context, just to reuse good solutions for old problems.
However, working with Spring, it’s easy to recognize that Patterns must be adapted to Spring, since some of them do not make sense when working with Spring.
I will elaborate the most important and famous ones here in the context of Spring usage.

Factory Method Pattern

For two reasons, the Factory Method Pattern is not really useful in the Spring context:

  1. Spring’s BeanFactory implements a kind of Factory Pattern itself. It is easy to use different BeanFactories and therefore create different beans according to context. For example, using several XML-configurations and instantiating them in different ApplicationContexts gives you several bean factories configured with XML.
  2. Since with Spring injecting different beans is done by XML-configurations and pseudo-Singletons are used, the advantage of having a single point of changing bean instantiation is inherent to Spring.

Nevertheless, I implemented the almost original Factory Method Pattern below.

Usually, the beans-factory-lookup-method-injection is referred as the factory method implementation in spring. Thought this is certainly true with respect to the actual pattern, it is difficult to see the advantage of this approach in contrast to just injecting a bean. This is even more transparent and there is no magic in it.
To actually make use of creating different objects, I made up the following scenario, which allows for creating different objects during runtime. There is nothing special in it, just plain usage of Spring, magic excluded.

package sample.factory;

public enum Type {

	FIRST, SECOND;

}

An interface to identifying the objects:

package sample.factory;

public interface ClassType {

	Type getId();

}

First type of object:

package sample.factory;

public class FirstType implements ClassType {

	@Override
	public Type getId() {
		return Type.FIRST;
	}

	@Override
	public String toString() {
		return getId().toString();
	}

}

Second type of object:

package sample.factory;

public class SecondType implements ClassType {

	@Override
	public Type getId() {
		return Type.SECOND;
	}

	@Override
	public String toString() {
		return getId().toString();
	}

}

The factory itself, objects will be injected:

package sample.factory;

import java.util.Map;

public class FactorySample {

	private Map<Type, ClassType> identifiers;

	public void setConcreteClasses(Map<Type, ClassType> i) {
		this.identifiers = i;
	}

	public ClassType createClassOfType(Type type) {
		switch (type) {
			case FIRST : return identifiers.get(type);
			case SECOND : return identifiers.get(type);
			default : return null;
		}
	}

}

Main class which retrieves factory bean and creates a object of second type:

package sample.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		ApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");
		FactorySample factory = (FactorySample) app.getBean("factory");
		ClassType i = factory.createClassOfType(Type.SECOND);
		System.out.println(i);
	}

}

Finally, the spring config (entry key Strings are converted automagically by Spring):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

	<bean id="factory" class="sample.factory.FactorySample">
		<property name="concreteClasses">
			<map>
				<entry key="FIRST">
					<ref local="FirstType" />
				</entry>
				<entry key="SECOND">
					<ref local="SecondType" />
				</entry>
			</map>
		</property>
	</bean>

	<bean id="FirstType" class="sample.factory.FirstType"/>

	<bean id="SecondType" class="sample.factory.SecondType"/>

</beans>