Design patterns are typical solutions to common problems in software design. Each pattern is like a blueprint that you can customize to solve a particular design problem in your code.
Design patterns are mainly classified into three types:
- Creational
- Structural
- Behavioural
Structural design patterns help manage the creation of objects
- Helps in places where we have a lot of properties to be passed while object creation
- Without it, we need to pass everything in constructor while remembering the order of the arguments
- Creating objects with high number of properties without builder pattern will be cumbersome and difficult to read
- Help us manage the type of object that is created based on some criteria
- Instead of defining that logic everywhere, we use factory to have that logic in one place
- In future if that criteria changes, we only have the change factory logic
- Useful at situations where we want to create a duplicate object without actually creating it again
- Helps in cases where we do some DB calls to create an object by avoiding DB calls on every duplication
- Only a single instance of a class is allowed
- Techniques like double checked locking are used to improve performance.
- Enum implementation is also for an easy implementation.
Structural design patterns help manage the composition of the objects
- Helps in places where we have a new system/ library that requires data in a different format than current system
- Using adapter, no logic is needed to be changed in old system to communicate with the new system/ library
- When an object is containing multiple objects that have similar properties
- Useful in places where we have a tree like structure or hierarchies
- Allows behavior to be added to individual object without affecting the behavior of objects from the same class
- Provides an alternative to subclassing for extending functionality
- Used in places where we have two or more interfaces performing same functionality
- A single facade interface is introduced for simplicity
- All functional calls to those interfaces can be served by a single facade interface.
- The difference in state/context between those interfaces can be used to route function calls
- Used for controlling access to specific functionalities of a class.
- Where allowed operations are dependent upon the role of the user.
Structural design patterns help manage the interaction of the objects with each other
- Used to observe changes happening in another object.
- Useful in cases where pub-sub like logic needs to be implemented.