mercredi 1 mars 2017

Instead of letting the subclasses provide the object creation implementation why not product obtained using polymorphism

As per GOF book, Factory method pattern

Define an interface for creating an object, but let the subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclass.

Structure of the pattern

public abstract class Factory {
    public abstract IProduct createProduct();
    private void performCriticalJob(){
        IProduct product = createProduct();
        product.serve();
    }
    public void executeJob(){
        //some code
        performCriticalJob();
        //some more code
    }
}

  1. Factory needs an object (whose concrete class is not known or whose concrete class may change as per the different application type ) to perform a task.

  2. As it does not know which class to instantiate, one standard contract is set for the type of object needed, this contract is put in an Interface.

  3. Base factory class declares an abstract method to return an object of type as above defined interface. It lets subclasses decide and provide the implementation of object creation.

  4. For completion of the task it needs an object which it simply fetches by calling the abstract method.

Question To achieve the intent in the scenarios as above (defined scenario for Factory method pattern) of this pattern why just normal polymorphism is not being used as below

public abstract class Factory {
    private void performCriticalJob(IProduct product){
        product.serve();
        //some code
    }
    public void executeJob(IProduct product){
        //some code
        performCriticalJob(product);
        //some more code
    }
}

Aucun commentaire:

Enregistrer un commentaire