Design Patterns are developed to solve different and frequent software problems related to design and interfaces. It’s an excellent way of working with already proved and tested paradigms through templates and tricks that can make the software development procedure much easier and apprehensive.
They are useful to establish a common vocabulary among designers, to standardize working procedures, to generate catalogs of reusable elements and to facilitate the approach of design aspects and components.
There are different types of patterns: Structural Patterns, that specify the way in which some classes relate to others, and Behavior Patterns, that allow managing algorithms, relationships, and responsibilities between objects.
The Decorator Pattern allows adding behavior dynamically to an object, without affecting the behavior of other objects of the same class. When it is necessary to use it? When it is needed to add or remove responsibilities to objects dynamically, and when we want to modify the functionality of an entity without affecting the uses of it in other places of our project.
The diagram of the Decorator Pattern is structured in the following way:
- Component: interface with the responsibilities to add.
- Concrete component: object to which responsibilities can be added.
- Decorator: has a reference to the associated component.
- Concrete decorator: adds responsibilities to the component.
On the other hand, the Observer Pattern defines a dependency of type one to many between objects, so that when one of the objects changes its state, it notifies this change to all the dependents. When it is necessary to use it? When the change in one object must be reflected in another avoiding the coupling.
The Observer Pattern structure is composed in the following way:
- Subject: interface to add and delete observers.
- Observer: an interface that defines the method that the subject uses to notify status changes.
- ConcreteSubject: notifies observers when the state changes.
- ConcreteObserver: implements the Observer interface and the action it will take when the subject changes state.