# Factory Pattern

## Intent

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

## When to use

1. You can't know the type of object you want to create until runtime.
2. You want to encapsulate the object creation logic if some complexity or business logic takes place, or for easier extraction and modification later on.

## Structure

![](/files/-MKQ8_ieDbUS1fRLKa_G)

* Product: declares the interface of the object the factory method will create.
* ConcreteProduct: implements the Product interface.
* Creator: declares the factory method which returns an object of type Product, it may also implement a basic factory method which can be overriden by subclasses.
* ConcreteCreator: implements the factory method to return an instance of a ConcreteProduct.

## Implementation

Factory method can have 2 types of implementations:

1. Relying on subclasses for the Factory that returns different kind of ConcreteProducts (doesn't violate the O/C Principle, allows for polymorphism, and Dependency Injection).
2. Relying on a paramater (Parametrized Factory) to determine the type of the ConcreteProduct needed.

## Examples

|                                                             Source Code                                                             |   UML   |
| :---------------------------------------------------------------------------------------------------------------------------------: | :-----: |
| [Example 1](https://github.com/khaled-hamam/design-patterns-explained/blob/master/library/creational-patterns/factory/example_1.ts) | // TODO |
| [Example 2](https://github.com/khaled-hamam/design-patterns-explained/blob/master/library/creational-patterns/factory/example_2.ts) | // TODO |
| [Example 3](https://github.com/khaled-hamam/design-patterns-explained/blob/master/library/creational-patterns/factory/example_3.ts) | // TODO |

You can find the tests [here](https://github.com/khaled-hamam/design-patterns-explained/blob/master/library/creational-patterns/factory/index.test.ts).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://khaled-hamam.gitbook.io/design-patterns-explained/library/creational-patterns/factory.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
