:::: MENU ::::

Factory pattern


It is a creational pattern design in where objects belonging to a class jerarchy are encapsulated.

Utility

By implementating this pattern we will manage only one object type, because internally the most suitable for us will be instantiated.

Example

We create a class structure. A mother class (Animal) that will have two children (Cat) and (Dog).

The mother has to be abstract, in order to avoid its instantiation. We include an abstract method (that will be the one we will define in the children).

Animal.java

package com.luisgomezcaballero.factory_pattern_demo;

public abstract class Animal {
	
	public abstract String getSound();
	
}

We create the two children classes by doing them extend from their mother.

We overwrite the abstract method (by doing it different in every class, and to check that they return a different result in every case because we are instantiating two different classes).

Cat.java

package com.luisgomezcaballero.factory_pattern_demo;

public class Cat extends Animal {

	@Override
	public String getSound() {
		return "Miaw";
	}

}

Dog.java

package com.luisgomezcaballero.factory_pattern_demo;

public class Dog extends Animal {

	@Override
	public String getSound() {
		return "Warf";
	}

}

Now, we apply the pattern by generating a factory.

AnimalFactory.java

package com.luisgomezcaballero.factory_pattern_demo;

public class AnimalFactory {

	public static Animal getAnimal(String type) {
		if ("cat".equals(type)) {
			return new Cat();
		} else {
			return new Dog();
		}
		
	}
}

And finally we can test its functionality in a main class.

Main.java

package com.luisgomezcaballero.factory_pattern_demo;

public class Main {

	public static void main(String[] args) {
		
		Animal animal1 = AnimalFactory.getAnimal("cat");
		System.out.println("animal1 says: " + animal1.getSound());
		
		Animal animal2 = AnimalFactory.getAnimal("dog");
		System.out.println("animal2 says: " + animal2.getSound());
		
	}

}

Repositorio

The code of this project can be located at https://github.com/luisgomezcaballero/factory-pattern-demo.


So, what do you think ?