You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
15 Hrs
38 Min
22 Seg

Patr贸n Factory en Python

17/27
Resources

What is the Factory Pattern?

The Factory Pattern is one of the most important design patterns in software development, and its main feature is its ability to create objects without the need to specify the exact class. This is achieved through the use of interfaces, abstractions or protocols. This pattern encapsulates the creation logic, centralizing the decisions on what classes to create and how to do it, thus allowing greater flexibility and scalability in the system.

How does the Factory Pattern work?

The essence of the Factory Pattern lies in the creation of a class called 'Factory', which contains a method that instantiates and returns objects based on certain parameters. By applying this pattern, the place where creation decisions are made is centralized, which makes it easier to maintain and scale the system.

For example, in a class diagram one could visualize a high-level class called PaymentService, which interacts with PaymentFactory. The latter has a GetProcessor method that decides which of the payment processors to use, based on a specific type passed as a parameter. Thus, PaymentFactory centralizes the logic of deciding which processor to use, allowing to easily integrate new processors in the future.

When is it appropriate to apply this pattern?

The Factory Pattern becomes an excellent choice in the following scenarios:

  • When there are multiple classes that share a common interface. This is especially useful in systems where the use of different strategies is required to solve similar problems.
  • When the creation of objects requires complex decision logic. If there are many variables to decide which class to select, this pattern helps to simplify the process and establish centralized control.

In addition, it works very well together with the Strategy pattern, facilitating the selection of appropriate strategies for each use case.

How to implement it effectively?

To implement the Factory Pattern, follow these steps:

  1. Define common interfaces: Make sure that all possible classes to be instantiated implement a common interface or abstraction.
  2. Create the Factory class: Develop a class that has a method in charge of receiving parameters. This method must determine which class to instantiate.
  3. Use the Factory in the client code: Whenever you need to create an instance, use the Factory to obtain the correct object.

Thus, by integrating the Factory Pattern, we can create more flexible and scalable applications, allowing us to modify and integrate new functionalities without altering the fundamental structure of the system.

Get to know the Factory Pattern and experience its potential. This practice is crucial for any developer who wants to build robust and flexible systems. Keep learning and applying these patterns in your projects!

Contributions 6

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

El patr贸n Factory en Python se caracteriza por: 1. **Abstracci贸n**: Crea objetos sin especificar la clase exacta, utilizando interfaces o abstracciones. 2. **Encapsulamiento**: Centraliza la l贸gica de creaci贸n de objetos, simplificando la instancia de clases. 3. **Flexibilidad**: Permite a帽adir nuevos tipos de objetos sin modificar el c贸digo existente. **Cu谩ndo aplicarlo**: - Cuando hay m煤ltiples clases que comparten una interfaz. - Cuando la creaci贸n de objetos requiere l贸gica compleja. **C贸mo aplicarlo**: - Crea una clase Factory con un m茅todo que instancie objetos basados en par谩metros. Usa el Factory donde se requieran instancias, facilitando cambios futuros.
El Patr贸n Factory es un patr贸n de dise帽o creacional que permite crear objetos sin especificar la clase exacta del objeto que se va a instanciar. Este patr贸n utiliza interfaces o clases abstractas para encapsular la l贸gica de creaci贸n, facilitando as铆 la flexibilidad y la escalabilidad del c贸digo. Se utiliza especialmente cuando hay m煤ltiples clases que comparten una interfaz com煤n y se requiere decidir cu谩l de ellas crear en tiempo de ejecuci贸n. Esto centraliza la l贸gica de creaci贸n, haciendo que el sistema sea m谩s mantenible y extensible.
El \*\*Patr贸n Factory\*\* es un patr贸n de dise帽o creacional que proporciona una manera de crear objetos sin exponer la l贸gica de creaci贸n al cliente. En su lugar, el cliente utiliza un m茅todo com煤n para crear las instancias necesarias. Este patr贸n es 煤til cuando la creaci贸n de objetos es compleja o depende de condiciones espec铆ficas. \### Conceptos Clave del Patr贸n Factory 1\. \*\*Encapsulaci贸n\*\*: La l贸gica de creaci贸n de objetos est谩 encapsulada en un m茅todo, funci贸n o clase espec铆fica. 2\. \*\*Simplicidad para el Cliente\*\*: El cliente no necesita conocer los detalles sobre qu茅 clase exacta est谩 siendo instanciada. 3\. \*\*Extensibilidad\*\*: Es f谩cil a帽adir nuevas clases sin modificar el c贸digo del cliente. \### Tipos de Patr贸n Factory 1\. \*\*Simple Factory\*\*: Tiene un 煤nico m茅todo para crear instancias de diferentes clases. 2\. \*\*Factory Method\*\*: Define una interfaz para crear objetos, dejando las subclases responsables de definir qu茅 clase instanciar. 3\. \*\*Abstract Factory\*\*: Proporciona una interfaz para crear familias de objetos relacionados o dependientes. \--- \### Implementaci贸n del Patr贸n Factory en Python Supongamos que estamos desarrollando un sistema para generar notificaciones (correo electr贸nico, SMS y push). Utilizaremos una \*\*Simple Factory\*\* para gestionar estas instancias. \#### Paso 1: Crear una Interfaz Com煤n Definimos una clase base que todas las notificaciones implementar谩n. ```python from abc import ABC, abstractmethod class Notification(ABC): @abstractmethod def notify(self, message: str): """Env铆a una notificaci贸n con el mensaje dado.""" pass ``` \#### Paso 2: Implementar Clases Concretas Creamos clases espec铆ficas para cada tipo de notificaci贸n. ```python class EmailNotification(Notification): def notify(self, message: str): print(f"Enviando correo electr贸nico: {message}") class SMSNotification(Notification): def notify(self, message: str): print(f"Enviando SMS: {message}") class PushNotification(Notification): def notify(self, message: str): print(f"Enviando notificaci贸n push: {message}") ``` \#### Paso 3: Crear la F谩brica La f谩brica centraliza la l贸gica para instanciar las notificaciones seg煤n el tipo solicitado. ```python class NotificationFactory: @staticmethod def create\_notification(notification\_type: str) -> Notification: if notification\_type == "email": return EmailNotification() elif notification\_type == "sms": return SMSNotification() elif notification\_type == "push": return PushNotification() else: raise ValueError(f"Tipo de notificaci贸n desconocido: {notification\_type}") ``` \#### Paso 4: Usar el Patr贸n Factory Ahora podemos crear notificaciones sin preocuparnos por la l贸gica de instanciaci贸n. ```python \# Crear diferentes notificaciones usando la f谩brica notification1 = NotificationFactory.create\_notification("email") notification1.notify("隆Hola! Este es un correo electr贸nico.") notification2 = NotificationFactory.create\_notification("sms") notification2.notify("隆Hola! Este es un SMS.") notification3 = NotificationFactory.create\_notification("push") notification3.notify("隆Hola! Esta es una notificaci贸n push.") ``` \--- \### Ventajas del Patr贸n Factory 1\. \*\*Simplicidad para el Cliente\*\*: El cliente no necesita preocuparse por la l贸gica de creaci贸n de objetos. 2\. \*\*Centralizaci贸n\*\*: La l贸gica de creaci贸n se mantiene en un solo lugar, haciendo que el c贸digo sea m谩s f谩cil de mantener. 3\. \*\*Extensibilidad\*\*: Es sencillo a帽adir nuevas clases de notificaci贸n (o cualquier tipo de objeto) sin modificar la l贸gica existente en el cliente. 4\. \*\*Cumplimiento del Principio Abierto/Cerrado (OCP)\*\*: Podemos extender el sistema con nuevos tipos de objetos sin cambiar la f谩brica. \--- \### Consideraciones 1\. \*\*Acoplamiento\*\*: Si la f谩brica crece demasiado, puede volverse un punto de acoplamiento fuerte. 2\. \*\*Complejidad Inicial\*\*: Para problemas simples, el uso de una f谩brica puede parecer innecesario. \--- \### Variaci贸n: Usar Diccionarios en lugar de Condicionales Podemos simplificar la implementaci贸n de la f谩brica utilizando un diccionario para mapear tipos de notificaciones a sus clases concretas. ```python class NotificationFactory: \_notification\_classes = { "email": EmailNotification, "sms": SMSNotification, "push": PushNotification, } @staticmethod def create\_notification(notification\_type: str) -> Notification: notification\_class = NotificationFactory.\_notification\_classes.get(notification\_type) if not notification\_class: raise ValueError(f"Tipo de notificaci贸n desconocido: {notification\_type}") return notification\_class() ``` Esto elimina los condicionales, haciendo que el c贸digo sea m谩s limpio y f谩cil de mantener. \--- \### Conclusi贸n El \*\*Patr贸n Factory\*\* en Python es una herramienta poderosa para gestionar la creaci贸n de objetos, especialmente cuando el proceso de instanciaci贸n es complejo o depende de condiciones din谩micas. Este patr贸n mejora la organizaci贸n y extensibilidad del c贸digo, promoviendo pr谩cticas de dise帽o robustas.
```python from abc import ABC, abstractmethod # Producto abstracto class Transporte(ABC): @abstractmethod def mover(self): pass # Productos concretos class Coche(Transporte): def mover(self): return "El coche se est谩 moviendo por carretera" class Bicicleta(Transporte): def mover(self): return "La bicicleta se est谩 moviendo por el carril bici" # Clase creadora abstracta class CreadorTransporte(ABC): @abstractmethod def crear_transporte(self): pass # Creadores concretos class CreadorCoche(CreadorTransporte): def crear_transporte(self): return Coche() class CreadorBicicleta(CreadorTransporte): def crear_transporte(self): return Bicicleta() # Uso del patr贸n Factory Method def cliente(creador: CreadorTransporte): transporte = creador.crear_transporte() print(transporte.mover()) # Crear un coche cliente(CreadorCoche()) # Salida: "El coche se est谩 moviendo por carretera" # Crear una bicicleta cliente(CreadorBicicleta()) # Salida: "La bicicleta se est谩 moviendo por el carril bici" ```
falto agregar la documentaci贸n que se fue agregando a todos las otras clases.
No s茅 si puede dcirse que lo aplique pero cuando tengo esos casos tengo una clase factory que recibe, por decir, el nombre de un exchange (mi proyecto es un bot de trading) y este "factory" busca en un diccionario que tengo donde la llave es el nombre del exchange y el valor la referencia de la clase y ya crea el objeto y lo retorna