Monday, July 21, 2014

Factory Method Implementation

Factory Method implementation:

// Define an interface that will be implemented by all sub-classes
interface Pet {
    public String speak();
}

// Create subclass
class Dog implements Pet {
    @Override
    public String speak() {
        return "Bark, bark";
    }
}

// Create subclass
class Duck implements Pet {
    @Override
    public String speak() {
        return "Quack, quack";
    }
}

// Creating a class that has Factory method
// to instatiate an object of subclass based on type
class PetFactory {
    public Pet getPet(String petType) {
        Pet pet = null;
       
        if("bark".equals(petType))
            pet = new Dog();
        else if("quack".equals(petType))
            pet = new Duck();
       
        return pet;
    }
}

public class FactoryMethodExample {
    public static void main(String[] args) {
        // Creating the factory
        PetFactory petFactory = new PetFactory();
       
        // Factory instantiate an object based on type
       
        // Note here, we are programming against an Interface
        Pet p = petFactory.getPet("bark");
       
        System.out.println(p.speak());
    }
}

No comments:

Post a Comment