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
}
}
-
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.
-
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.
-
Base factory class declares an
abstract
method to return an object of type as above definedinterface
. It lets subclasses decide and provide the implementation of object creation. -
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