Factory Design Pattern

The Factory Design Pattern is one of the most used design patterns. It is classified as a creational pattern under the Gang of Four (GoF). The intention behind the Factory Design Pattern is to encapsulate complex instantiation logic from the client code and references objects through a common interface.

There are generally three major components in implementing Factory Design Pattern. They are:

Design

designPatterns-FactoryPattern.png

Interface

Animal.java

public interface Animal {
    public void move();
}

Concrete Classes

Dog.java

public class Dog implements Animal {
    @Override
    public void move() {
        System.out.println("Dog::move()");
    }
}

Cat.java

public class Cat implements Animal {
    @Override
    public void move() {
        System.out.println("Cat::move()");
    }
}

Cow.java

public class Cow implements Animal {
    @Override
    public void move() {
        System.out.println("Cow::move()");
    }
}

Factory Class

AnimalFactory.java

public class AnimalFactory {
    public static final int DOG = 0;
    public static final int CAT = 0;
    public static final int COW = 0;

    public Animal getAnimal(int type) {
        if(type == DOG)
            return new Dog();
        else if(type == CAT)
            return new Cat();
        else if(type == COW)
            return new Cow();
        return null;
    }
}

This article is my 23rd oldest. It is 208 words long, and it’s got 0 comments for now.