2010-09-07

Factory Class Pattern with Interface

A sample implementation of the factory OO pattern incl. interface which is used in many languages. This example is implemented in Java but the concept is the same in all languages: Creating a factory class that creates settings/environment/parameter-dependent classes. This pattern example can be easily translated into .NET/C#. To get the complete demo code quickly, just pull its source code from this Mercurial repo.
class Cat extends Mammal {
    String doWalking() {
        return "Cat has been Informed to perform Walk Operation";
    }
}

class Dog extends Mammal {
    String doWalking() {
        return "Dog has been Informed to perform Walk Operation";
    }

class Main {
    private static MammalFactory forDogs = new MammalFactory() {
        @Override
        public Mammal createMammal() {
            System.out.println("Dog created...");
            return new Dog();
        }
    };
    private static MammalFactory forCats = new MammalFactory() {
        @Override
        public Mammal createMammal() {
            System.out.println("Cat created...");
            return new Cat();
        }
    };

    public static void main(String[] args) {
        new MammalClient(forDogs).createAndLetWalk();
        new MammalClient(forCats).createAndLetWalk();
    }

abstract class Mammal {
    abstract String doWalking();

class MammalClient {
    private final MammalFactory factory;

    MammalClient(MammalFactory factory) {
        this.factory = factory;
    }

    void createAndLetWalk() {
        factory.createMammal().doWalking();
        System.out.println("\t...let walk.");
    }

interface MammalFactory {
    Mammal createMammal();