Creational Patterns
NEED++++
Optimal way of creating the object for a given problem1.Singleton:
Creating an unique object for a class and give a global pointer/method for accessing the object2.Factory method:
- Creating an object of a class from a group of classes.
- Using this pattern, we defer the object creation logic of a group of classes from client to Factory class.
- Here, creation logic involves picking out the right class from the group of classes for a given i/p , creating an object and returning it.
3.Abstract Factory:
It overcomes the problems existing in Factory method pattern. In Factory pattern, objects creational logic is tightly coupled to the factory method in factory class. So, adding new product/sub products to the group demands code change in Factory Class.(Less maintainable)With Abstract factory, we push the object creation logic of every product/Sub product to an associated factory class. so, whenever a new product is added to the group.A new factory class has to be created which creates the Product/Sub products if exists. So, whenever a client wants to create an object of a specific product. The client creates the Specific factory instance and populates the necessary arguments which are enough for the factory to create a product instance.
Construct
- getProduct(AbstractFactory abstractFactory){factory.createProduct()}
4.Builder:
Helps in creating a complex object step by step rather than creating in 1 shot.Useful in scenarios where we have a class with 10 arguments. With different combination of arguments, we have to create different constructors to support the instance creation which is not a feasible approach.
So, instead of creating too many constructors. we will wrap the constructor of the product inside the builder class and expose this builder class to the client.
Now, this is Builder class's will take the responsibility of creating the object step by step and returns the final product.
5.Prototype:
Used in scenarios where the instance creation process is resource consuming/time taking/could be error prone(might not get the instance as expected because the creation process is tedious).In such scenarios, we clone the object prototype and share it client rather than allowing client to create a new object. Client can later modify this prototype as per his/her requirements.
In java it can be achieved through cloning. The object for which we are creating prototype has to be cloned and we should provide the clone implementation(deep/shallow - requirement specific)
Comments
Post a Comment