Skip to content

Commit

Permalink
feat(creational): ✨ add design pattern factory method (#51)
Browse files Browse the repository at this point in the history
Closes #50
  • Loading branch information
jeresoftx committed Sep 14, 2023
1 parent 11ca29d commit 5f5b1b4
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/_sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

- [Home](/)
- [Creational Design Patterns](/creationalPatterns/creationalPatterns.md)
- Factory method
- [Factory method](/creationalPatterns/factoryMethod.md)
- Abstract Factory
- Builder
- [Prototype](/creationalPatterns/prototype.md)
Expand Down
39 changes: 39 additions & 0 deletions docs/creationalPatterns/factorymethod.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Dessing Pattern Prototype

## Description

The Factory Method design pattern is a creational pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. In other words, this pattern defines an interface for creating an object but lets derived or subclassed classes decide which concrete class to implement and create.

**Key elements of the Factory Method pattern:**

1. **Product:** It is an interface or abstract class that defines the structure of the objects that the Factory Method will create.

2. **Concrete Product:** These are concrete classes that implement the Product interface. Each of these classes represents a specific type of product.

3. **Creator:** It is an interface or abstract class that declares the Factory Method, which is a method for creating an object of the Product. It may also contain methods to operate on the created products.

4. **Concrete Creator:** These are concrete classes that implement the Creator and thus the Factory Method. Each Concrete Creator decides which specific type of Concrete Product to create.

**Characteristics and advantages of the Factory Method pattern:**

- **Flexibility:** The Factory Method allows derived classes to choose what type of object to create. This makes object creation more flexible and extensible.

- **Decoupling:** It helps reduce coupling between the Creator and Concrete Product classes since the Creator doesn't need to know the exact concrete classes it will create.

- **Reusability:** It facilitates code reuse, as the same Creator can be used with different Concrete Products.

- **Extensibility:** It allows adding new types of Concrete Products without modifying existing code.

The Factory Method pattern is commonly used in libraries and frameworks where an interface for object creation is provided, but the concrete implementation is delegated to the classes using the library or framework.

In summary, the Factory Method is a powerful technique for object creation that promotes flexibility, decoupling, and extensibility in software design.

## Ejemplos de código

<!-- tabs:start -->

#### **Typescript**

[factoryMethod.py](https://raw.githubusercontent.com/jeresoftx/design-patterns/main/src/creationalPatterns/factoryMethod/factoryMethod.ts ':include :type=code')

<!-- tabs:end -->
8 changes: 4 additions & 4 deletions docs/es-mx/_sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

- [Inicio](/)
- [Patrones Creacionales](/creationalPatterns/creationalPatterns.md)
- Factory method
- [Método de fabrica](/creationalPatterns/factoryMethod.md)
- Abstract Factory
- Builder
- [Prototype](/creationalPatterns/prototype.md)
- [Prototipo](/creationalPatterns/prototype.md)
- [Singleton](/creationalPatterns/singleton.md)
- [Patrones de Comprotamiento](/behavioralPatterns/behavioralPatterns.md)
- Chain of responsibility
Expand All @@ -14,13 +14,13 @@
- Iterator
- Mediator
- Memento
- [Observer](/behavioralPatterns/observer.md)
- [observador](/behavioralPatterns/observer.md)
- State
- Strategy
- Template method
- Visitor
- [Patrones Estructurales](/structuralPatterns/structuralPatterns.md)
- [Adapter](/structuralPatterns/adapter.md)
- [Adaptador](/structuralPatterns/adapter.md)
- Bridge
- Composite
- Decorator
Expand Down
39 changes: 39 additions & 0 deletions docs/es-mx/creationalPatterns/factoryMethod.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Patrón de diseño prototipo

## Descripción

El patrón de diseño Factory Method (Método de Fábrica) es un patrón creacional que proporciona una interfaz para crear objetos en una superclase, pero permite a las subclases alterar el tipo de objetos que se crearán. En otras palabras, este patrón define una interfaz para crear un objeto, pero permite que las clases derivadas o subclases decidan qué clase concreta implementar y crear.

**Elementos clave del patrón Factory Method:**

1. **Producto (Product):** Es una interfaz o clase abstracta que define la estructura de los objetos que el Factory Method creará.

2. **Concrete Product:** Son las clases concretas que implementan la interfaz del Producto. Cada una de estas clases representa un tipo específico de producto.

3. **Creator (Creador):** Es una interfaz o clase abstracta que declara el Factory Method, que es un método para crear un objeto del Producto. También puede contener métodos para operar sobre los productos creados.

4. **Concrete Creator:** Son las clases concretas que implementan el Creator y, por lo tanto, el Factory Method. Cada Concrete Creator decide qué tipo específico de Concrete Product debe crear.

**Características y ventajas del patrón Factory Method:**

- **Flexibilidad:** El Factory Method permite a las clases derivadas elegir qué tipo de objeto crear. Esto hace que la creación de objetos sea más flexible y extensible.

- **Desacoplamiento:** Ayuda a reducir el acoplamiento entre las clases Creator y Concrete Product, ya que el Creator no necesita conocer las clases concretas exactas que va a crear.

- **Reutilización:** Facilita la reutilización del código, ya que el mismo Creator puede utilizarse con diferentes Concrete Products.

- **Extensibilidad:** Permite agregar nuevos tipos de Concrete Products sin modificar el código existente.

El patrón Factory Method se utiliza comúnmente en bibliotecas y frameworks donde se proporciona una interfaz para crear objetos, pero la implementación concreta se delega a las clases que utilizan la biblioteca o el framework.

En resumen, el Factory Method es una técnica poderosa para la creación de objetos que promueve la flexibilidad, el desacoplamiento y la extensibilidad en el diseño de software.

## Ejemplos de código

<!-- tabs:start -->

#### **Typescript**

[factoryMethod.py](https://raw.githubusercontent.com/jeresoftx/design-patterns/main/src/creationalPatterns/factoryMethod/factoryMethod.ts ':include :type=code')

<!-- tabs:end -->
26 changes: 26 additions & 0 deletions docs/es-mx/creationalPatterns/singleton.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,29 @@ El patrón Singleton se utiliza en situaciones donde se requiere una única inst
Un ejemplo común de uso del patrón Singleton es en el manejo de registros de eventos, sistemas de configuración, controladores de bases de datos, administradores de caché y administradores de hilos, entre otros.

La implementación exacta del patrón Singleton puede variar según el lenguaje de programación, pero los conceptos clave mencionados anteriormente son universales en todas las implementaciones del patrón.

## Código de ejemplo

<!-- tabs:start -->

#### **Typescript**

[singleton.ts](https://raw.githubusercontent.com/jeresoftx/design-patterns/main/src/creationalPatterns/singleton/singleton.ts ':include :type=code')

#### **Python**

[singleton.py](https://raw.githubusercontent.com/jeresoftx/design-patterns/main/src/creationalPatterns/singleton/singleton.py ':include :type=code')

#### **Kotlin**

[singleton.kt](https://raw.githubusercontent.com/jeresoftx/design-patterns/main/src/creationalPatterns/singleton/singleton.kt ':include :type=code')

#### **Ruby**

[singleton.rb](https://raw.githubusercontent.com/jeresoftx/design-patterns/main/src/creationalPatterns/singleton/singleton.rb ':include :type=code')

#### **PHP**

[singleton.php](https://raw.githubusercontent.com/jeresoftx/design-patterns/main/src/creationalPatterns/singleton/singleton.php ':include :type=code')

<!-- tabs:end -->
50 changes: 50 additions & 0 deletions src/creationalPatterns/factoryMethod/factoryMethod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Interface for Factory Method
interface Product {
operation(): string;
}

// Concrete class implementing Product
class ConcreteProductA implements Product {
operation(): string {
return 'Product A';
}
}

// Another concrete class implementing Product
class ConcreteProductB implements Product {
operation(): string {
return 'Product B';
}
}

// Interface defining the factory method
interface Creator {
factoryMethod(): Product;
}

// Concrete class implementing Creator and creating ConcreteProductA
class ConcreteCreatorA implements Creator {
factoryMethod(): Product {
return new ConcreteProductA();
}
}

// Another concrete class implementing Creator and creating ConcreteProductB
class ConcreteCreatorB implements Creator {
factoryMethod(): Product {
return new ConcreteProductB();
}
}

// Using the Factory Method pattern
function clientCode(creator: Creator) {
const product = creator.factoryMethod();
console.log(product.operation());
}

// Example of usage
console.log('Client: Using ConcreteCreatorA');
clientCode(new ConcreteCreatorA());

console.log('Client: Using ConcreteCreatorB');
clientCode(new ConcreteCreatorB());

0 comments on commit 5f5b1b4

Please sign in to comment.