Creational Design Pattern

Creational Design Pattern

Creational design patterns are like toolkits for creating objects efficiently, enabling flexibility and reusability in software development.

There are several creational design patterns, each serving different purposes and addressing various aspects of object creation:

  1. Singleton Pattern: Ensures that a class has only one instance and provides a global point of access to that instance.
  2. Factory Method Pattern: Defines an interface for creating an object, but allows subclasses to alter the type of objects that will be created.
  3. Abstract Factory Pattern: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
  4. Builder Pattern: Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
  5. Prototype Pattern: Creates new objects by copying an existing object, known as the prototype, thereby avoiding the need for subclassing.


Today, I am going to talk about one of the most used design pattern Factory Method Pattern in software development.

Factory Method

When designing a system for file uploads to cloud providers, it's essential to anticipate future requirements. While initially supporting only one provider, such as AWS S3, the architecture should be flexible enough to seamlessly integrate additional providers like Google Cloud or Azure.

This is where the Factory Design Pattern shines. By encapsulating the creation of cloud storage uploaders within a factory, the system achieves high cohesion and low coupling. This means that each component is focused on its specific responsibility, and changes can be made without affecting other parts of the system unnecessarily.

With the Factory Design Pattern, adding support for new cloud providers becomes a straightforward process. Instead of scattering provider-specific logic throughout the codebase, a new uploader implementation can be added to the factory without impacting existing functionality. This promotes scalability, maintainability, and ease of extension.

By embracing this design pattern, the system not only meets current requirements efficiently but also anticipates future needs with grace and adaptability. As the system evolves, the Factory Design Pattern ensures that it remains robust, modular, and easy to maintain, making it a cornerstone of its architectural design.


let's create a class diagram of above scenarios:

Factory Method


In this example:

  • We define an abstract class CloudUploader which serves as the interface for uploading files to cloud providers.
  • Concrete implementations of CloudUploader are provided for AWS S3, Google Cloud Storage, and Azure Blob Storage.
  • The CloudUploaderFactory class provides a static method create_uploader() to create the appropriate uploader based on the specified cloud provider.
  • Example usage demonstrates how to create an uploader using the factory and upload a file to the selected cloud provider.


Now, its time to code in python.

from abc import ABC, abstractmethod


# Abstract class for cloud storage uploader
class CloudUploader(ABC):
    @abstractmethod
    def upload(self, file_path):
        pass


# Concrete implementation for AWS S3 uploader
class AWSS3Uploader(CloudUploader):
    def upload(self, file_path):
        # Code for uploading to AWS S3
        print(f"Uploading {file_path} to AWS S3")


# Concrete implementation for Google Cloud Storage uploader
class GoogleCloudStorageUploader(CloudUploader):
    def upload(self, file_path):
        # Code for uploading to Google Cloud Storage
        print(f"Uploading {file_path} to Google Cloud Storage")


# Concrete implementation for Azure Blob Storage uploader
class AzureBlobStorageUploader(CloudUploader):
    def upload(self, file_path):
        # Code for uploading to Azure Blob Storage
        print(f"Uploading {file_path} to Azure Blob Storage")


# Factory class to create cloud storage uploaders
class CloudUploaderFactory:
    @staticmethod
    def create_uploader(cloud_provider):
        if cloud_provider == "AWS":
            return AWSS3Uploader()
        elif cloud_provider == "Google":
            return GoogleCloudStorageUploader()
        elif cloud_provider == "Azure":
            return AzureBlobStorageUploader()
        else:
            raise ValueError("Unsupported cloud provider")



if __name__ == "__main__":
    file_path = "example_file.txt"
    
    # Choose the cloud provider
    cloud_provider = "AWS"  # Change this to "Google" or "Azure" to test with different providers
    
    # Create uploader using factory
    uploader = CloudUploaderFactory.create_uploader(cloud_provider)
    
    # Upload file
    uploader.upload(file_path)        

You can extend this pattern by adding more cloud providers and corresponding uploaders as needed.


conclusion

In conclusion, the Factory Design Pattern facilitates the creation of objects by encapsulating the instantiation process. In the provided example, it's employed to manage the creation of cloud storage uploaders, ensuring a clear separation of concerns and promoting code maintainability and scalability. By abstracting the uploader creation logic into a factory class, the system becomes more flexible and adaptable, allowing for seamless integration of new cloud providers in the future. This design pattern not only simplifies the client code but also enhances code reusability and modifiability, making it a valuable asset in software development.

要查看或添加评论,请登录

Er. Jiwan Gharti的更多文章

  • Design pattern

    Design pattern

    Design patterns typically describe the relationships and interactions between classes or objects, emphasizing the best…

  • Design Pattern:

    Design Pattern:

    In the realm of software development, the design phase plays a crucial role in laying the foundation for a successful…

社区洞察

其他会员也浏览了