Factory pattern

Factory pattern

software_development

The factory pattern is used when we want to create a object without knowing the specific class of the object but only the interface that it implements or the abstract class it extends.

A practical example

In our example we have a Drawer class that has a method that takes the name of a geometric shape and draws it.


class Drawer {
	public void draw(String name){
		Shape shape;

		if (name.equals("square")){
			shape = new Square();
		} else if (name.equals("triangle")){
			shape = new Triangle();
		} else if (name.equals("circle")){
			shape = new Circle();
		}

		shape.draw();
	}
}

interface Shape{
	void draw();
}

class Square implements Shape{
	[...]
}

class Triangle implements Shape{
	[...]
}

class Circle implements Shape{
	[...]
}

The drawer has to recognize which shape to draw and has a direct dependency to the Square, Triangle and Circle classes. How can we eliminate this direct dependency? We create a ShapeFactory class that handles the creation of the shape.


class ShapeFactory{
	public Shape create(String name){
		if (name.equals("square")){
			return new Square();
		} else if (name.equals("triangle")){
			return new Triangle();
		} else if (name.equals("circle")){
			return new Circle();
		}		

		throw new Exception();
	}
}

class Drawer {
	private ShapeFactory factory;

	public void draw(String name){
		Shape shape = factory.create(name);
		shape.draw();
	}
}

Now the Drawer class doesn’t know the exact class of the shape object that has been created and the direct dependency is gone. We could also remove the dependency with the ShapeFactory.


interface GeometryFactory{
	Shape create(String name);
}

class ShapeFactory implements GeometryFactory {
	public Shape create(String name){
		[...]
	}
}

class Drawer {
	private GeometryFactory factory;

	public void draw(String name){
		Shape shape = factory.create(name);
		shape.draw();
	}
}

Related News