Jesper
Jesper

Reputation: 2094

Design Pattern - Understanding Factory Pattern

I'm new to Design Patterns and am trying to learn how they typically look like. Right now I'm trying to understand the Factory Pattern, and I were wondering if my example is a typical Factory Pattern structure:

enter image description here

The ShapeFactory class uses the Shape-classes as dependencies(and are not instantiating them). Must the ShapeFactory instantiate the Shape-classes to be called a factory? Is this an accurate Factory Pattern diagram, or should the relation between the Shape-classes be associations instead?

Upvotes: 2

Views: 4551

Answers (2)

Gul Ershad
Gul Ershad

Reputation: 1771

Your diagram represents the "Factory Method Pattern" but, slightly it is missing some important class or object. Looks like shape class is Concrete Creator class. It doesn't have Creator class.

Basically, factory method design pattern has four classes and objects are involved:

1) Product : It defines the interface of objects the factory method creates.

2) ConcreteProduct: Implements the product interface.

3) Creator: It declares the factory method, which return an object of type product.

4) ConcreteCreator: It overrides the factory method to return and instance of a ConcreteProduct

Below diagram with slightly modification into your given diagram that represents the complete Factory Method Pattern:

enter image description here

Upvotes: 2

Jesper
Jesper

Reputation: 2094

Okay, I think I got the answer. This could be a factory pattern with methods(e.g. CreateCircle(), CreateRectangle etc.) with hidden dependencies in those methods that instantiate the classes.

I thought that a dependency was only for dependency injections, but I guess there could be a dependency when instantiating a class inside a method.

Upvotes: 0

Related Questions