mercredi 9 septembre 2020

Applicability for the Factory Method Pattern

I am confused at the factory-method pattern.

The below code is from "https://ift.tt/33d0sSd"

public interface Product { � }

public abstract class Creator 
{
    public void anOperation() 
    {
        Product product = factoryMethod();
    }
    
    protected abstract Product factoryMethod();
}

public class ConcreteProduct implements Product { � }

public class ConcreteCreator extends Creator 
{
    protected Product factoryMethod() 
    {
        return new ConcreteProduct();
    }
}

public class Client 
{
    public static void main( String arg[] ) 
    {
        Creator creator = new ConcreteCreator();
        creator.anOperation();
    }
}

Here is what I am confused : Creator creator = new ConcreteCreator();

In the site, We apply this pattern in two cases

  1. when a class can't anticipate the type of the objects it is supposed to create
  2. when a class wants its subclasses to be the ones to specific the type of a newly created object

But in the client code, we put 'new' keword with ConcreateCreator(and I know this is the concrete factory for the concrete product)

Dosen't it mean that the client exactly know what type of object he/she need to create?

Can anyone help me..?

Aucun commentaire:

Enregistrer un commentaire