Skip to main content

Python: Creational Design Patterns.


Creational Design Patterns.

Creational Design Patterns are one of the simplest sets of Design Patterns.

Advantages

  • Object creation can be independent of class implementation.

  • Adding support to a new type of object is very easy

  • The logic of object creation is hidden.

Creational Design Patterns Include

1) Singleton Design Pattern

This Pattern states that at a given time there should be only one `instance` of

any given object.

Thus reusing the object over and over again.


Singleton Object creation has only 2 sets of rules to be followed.

1) Object Must have only Single Instance Created.

2) There should be global access to the object created.


In Python Singleton is easiest to create for any given class.

Since the `__new__` is always a class method in python (until version 3.8).

You can always modify this method to make your object as a Singleton Object.

Advantages

  • Only a single instance is created hence low memory usage.

  • Faster Execution Since the Class is Not instantiated multiple times.

  • We got global access to the instance of the object.

Disadvantages

  • It's not easy to use the singleton method in a multithreaded environment, because we have to take care that multi-thread wouldn’t create a singleton object several times.

  • As they introduce the global state to the application, it makes the unit testing very hard.


2) Factory Pattern

Factory Pattern Defines a way to delegate the class that may or may not provide

similar kind of usage.


For e.g.

Consider a car that has a prerequisite to qualify as a car (4 wheels, body etc.)  

Now you need to create a new car that needs to have these predefined sets as well

as some extra features.

Then you define an abstract class a car having prerequisites and derive any new

class from this should implement

all the requisites and can add additional features.


Thus you can say that a Factory Design Pattern derives the way for Designing the

class.


A factory design pattern is used when we have a superclass with multiple sub-classes

and based on input, we need to return one of the sub-classes.

This pattern takes out the responsibility of instantiation of a class from the client

program to the factory class.

In Python, it is an abstract class in most cases.

Advantages

  • Factory pattern provides an approach to code for interface rather than implementation.

  • Factory pattern removes the instantiation of actual implementation classes from client code,

making it more robust, less coupled, and easy to extend.

  • Factory pattern provides abstraction between implementation and client classes via inheritance.

3) Abstract Factory Pattern

The abstract is a superset of a factory.

This set contains multiple factories that superset multiple properties for

an object where every object can have its multiple properties.

It groups the individual but related/dependent factories together without specifying

their concrete classes.


For e.g

Let's continue with the above car example in a little more detailed way.

As we said the car has few prerequisites to qualify as a car like 4 wheels.

However, this wheel may have its own set of properties such as type (allow, spokes,

etc.) shape, number, etc.

Hence in this case each requisite in the car can be its own factory pattern.

To define the car we may need to have a set of these factories combined to be able

to define the car correctly.

As a result, the class `Car` becomes a set of multiple factory methods having  wheels

as it subsets.


Thus Defining Abstract Factory.

Advantages

  • Abstract Factory provides a method to interface multiple groups.

  • This method is highly scalable since it allows multiple groups to be used.

4) Builder Pattern

Builder pattern allows you to create a complex set of an object when the creation of

the object is not possible directly.


For e.g. 

Let's Consider a serialization deserialization a complex JSON Object which consists

of the list, dictionary, and much more.


{
    "1st_key" : "some_data",
    "2nd_key" : [
            {
                "abc": "some_data",
                "def": "some_data"
            }, 
            {
               "abc": "some_data",
               "def": "some_data"
            }
          ] 
}

Example Json

So in this case builder pattern would have a class that stores the 1st level of

keys with `2nd_key` containing a List.

An object having the class a different class for a new class object.

Thus these classes can have their independent use and can be used and easily

replaced.


The intent of the Builder Pattern is to separate the construction of a complex

an object from its representation, so that the same construction process can create

different representations.

This type of separation reduces the object size. 

The design turns out to be more modular with each implementation contained in a

different builder object.

Adding a new implementation (i.e., adding a new builder) becomes easier.

The object construction process becomes independent of the components that make

up the object.

This provides more control over the object construction process.

Advantages

  • Clear separation between the construction and representation of an object.

  • Provides better control over the construction process.

  • Supports changing the internal representation of objects.

5) Prototype Pattern

Prototype pattern creates objects based on an existing object through cloning.

A prototype pattern is used when the object creation is a costly affair and requires

a lot of time and resources and you have a similar object already existing.

So this pattern provides a mechanismto copy the original object to a new object and then modify it according to our needs.


For example, an object is to be created after a costly database operation.

We can cache the object, returns its clone on the next request, and update the database

as and when needed thus reducing database calls.

Advantages

  • It reduces the need for sub-classing.

  • It hides the complexities of creating objects.

  • The clients can get new objects without knowing which type of object it will be.

  • It lets you add or remove objects at runtime.

Comments

Popular posts from this blog

Caching Algorithms (LRU Cache).

Implementation of LRU Cache Using Python What is a Cache? A cache is a hardware or software component that stores data so that future requests for that data can be served faster. The data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere.   What Is An LRU Cache? So an LRU Cache is storage of items so that future access to those items can be serviced quickly and an LRU policy is used for cache eviction. The Constraints/Operations      Lookup of cache items must be O(1)      Addition to the cache must be O(1) Our Structures Doubly Linked List: This will hold the items that our cache has. We will have n items in the cache. This structure satisfies the constraint for fast addition since any doubly linked list item can be added or removed in O(1) time with proper references. Hashtable: The hashtable will give us fast access to any item in the doubly linked list items to avoid O(n) search for items and the LRU entry (which will alw

Python 4.0.0 Will it be released ??

Python 4.0.0 As of July 28, 2021, Python version 2.9.6 has been released.  One of the biggest tasks for most of the python community was when the last major shift happened i.e. Python 2 Projects were to be migrated to Python 3. Most of us found the whole new change in the python package's way of writing, and at most of the places, the handling of Unicode was a mess. So the big picture stands when will Python Version 4.0 be released? Will the next major version of python bring any major changes in old codes? And at last, will it create a mess again for migrations of our Old Projects? Well as per the latest guidelines on Python.org unlike Python 2.9 and then Python3 the shift to Python 4 won't be so early. As per  Guido van Rossum, creator of the popular programming language, Python 4 is still far away. Python-Dev Community would be working on the Python 3.11.0a0 version of Python which is expected to be released by the end of the year 2021. So no all the major fuss about Python