1

I am confused at the factory-method pattern.

The below code is from "https://www.oodesign.com/factory-method-pattern.html"

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 where 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 ConcreteCreator (and I know this is the concrete factory for the concrete product).

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

Can anyone help me?

2
  • Yes, the client knows what concrete type he wants to create (somewhere in the code this decision should be made). The interface Creator is the contract how a product should be created in general. Commented Sep 10, 2020 at 7:09
  • Since then, If we change some code in the concrete creator like, we ask the client to put a parameter here, we still need to change the client code. Then what's the difference between using this pattern in our program and just make things with 'new' keyword? cause it looks there is no advantage about using this patttern... Commented Sep 10, 2020 at 8:42

1 Answer 1

2

In the Factory Method Pattern, the role of the Client is to provide a concrete Product to the abstract Creator.

This makes most sense when the abstract Creator lives in a third-party library and each Client is required to provide a Product by implementing its own subclass. In this scenario the Client is implementing an abstraction that it doesn't own.

Factory Method could be useful even when the Client owns the abstraction, if it needs to create multiple subclasses (i.e. multiple Products).

Factory Method does not make sense when the Client owns the abstraction and there is only one Product.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you share the source for this?
The ideas are derived from the GoF book. In particular, the Motivation section of the Factory Method chapter focuses exclusively on frameworks as the use case for this pattern.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.