The two factories

Have you ever hesitated between these two implementation of the Factory Pattern:

Factory #1

class AnimalFactory {
	public Animal createAnimal(String type)
				throws Exception {
		if (type.equals("dog"))
			return new Dog();
		if (type.equals("cat"))
			return new Cat();
		throw new Exception();

Factory #2

class AnimalFactory {
	public Animal createDog() {
		return new Dog();
	public Animal createCat() {
		return new Cat();

Which one is the best?

The point of the Factory Pattern is hiding concrete/volatile stuff when creating objects, by exposing an abstract/stable interface. Indeed, both of the two factories hide the concrete types Dog & Cat, and expose the abstract type Animal. This is very good.

The factory #2 is more clear and readable, but what if its interface changes frequently? For example, when you add a new method createElephant, all current clients of the factory will be affected unnecessarily because they never want to create elephants. By “affected” I mean recompiled and redeployed, not “source code changed” – indeed, those client code don’t change. In such a situation, the factory #1 is better though it is less readable.

So, the choosing of the best factory depends on how likely the code changes. Just remember to keep the factory interface stable to satisfy the Dependency Inversion Principle.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s