Skip to main content
1 of 3
Christophe
  • 82.3k
  • 11
  • 136
  • 202

According to GoF, the factory method:

defines an interface for creating and object, but let the subclasses decided which class to instantiate.

It involves a Creator class that has a FactoryMethod() which creates a Product, and ConcreteCreator which may be specializations of the Creator that override its template method and return ConcreteProducts. This means that the factory method can be embedded in any class where it could make sense, and not necessarily in distinct own class.

Your SimpleFactory implements in fact the GoF factory method pattern, with the following configuration:

  • instead of calling it FactoryMethod() you call it createBycicle() (naming detail, doesn't change anything for the pattern)
  • the SimpleFactory is the Creator (naming detail, doesn't change anything for the pattern)
  • the SimpleFactory provides a default implementation for the factory method (the other common variant is to have an abstract method, that needs to be defined in a concrete creator class).
  • the factory method is parmatrized and may return multiple kind of products (the other common variant is to have only one kind of product produced by the factory method)

So there is no difference! It's only a couple of choices you've made among those proposed in GoF (page 110-111).

Some additional remarks:

  • your default implementation creates in the factory a coupling with concrete products. This limits the extensibility of your design. You should consider raising an exception if the parameter is not among the authorized values: this would allow to extend your factory in compliance with LSP (allowing more values in the derived factories is weakening the preconditions, which is ok.
  • a terminological remark: a bicycle has by definition always exactly "two wheels" ("bi" = two). A cycle with one wheel is therefore not called "one wheel bicycle" but unicycle. And a cycle with three wheels is a tricycle. So I'd recommend renaming the classes accordingly, even if it doesn't change anything to your design ;-)
Christophe
  • 82.3k
  • 11
  • 136
  • 202