Choosing a good appropriate pattern would help make the code cleaner, easy to reuse, and limit the potential error, thereby speeding up the process of building.
Behavioral Patterns describe the communication between different objects.
Mediator, Observer, Visitor
1. Mediator
- Sometimes, we have components that interact with each other in chaotic order and may cause a conflict in logic or make the code really hard to maintain.
- Mediator Pattern aims to solve this problem, there would be a mediator class (middle man) to hold up and forward the actions to the appropriate component.
- By this technique, the components now depend only on a single mediator class instead of being coupled to dozens of their colleagues.
- In this pattern, there are a mediator and interactive classes
- Mediator would keep all the objects and the rule interaction of them inside it.
- Interactive classes also keep the connection with the mediator inside them as a variable in order to call the mediator’s method after they finish an action (if needed).
- Let's get an example, we have two objects (campaign and group) that have some restrictions. Group has two types such as
display
anddynamic
. If the campaign’s budget is less than 100$, the group can only set it todisplay
type and the group’sstart_date
can not be smaller than campaign’sstart_date
.
2. Observer
- We could apply this pattern when we have some objects observe the others’ actions to process its’ plan (subscription, callback)
- This pattern would have two object
- Publisher would hold a list of subscribers and notify them when needed.
- Subscriber/Observer would receive the notification from Publisher.
- For example, some students want to keep track of the notification of a course.
3. Visitor
- We use this pattern when some sub-classes have similar behaviors and we group these behaviors into a class with a specific purpose. eg: exporting file types.
- This pattern uses a technique called Double Dispatch, which helps to execute the proper method on an object without cumbersome conditionals.
- This pattern would have two objects such as
- Element is the object containing the splitting out behaviors for a specific purpose.
- Visitor is the object call to execute the behaviors. - Let’s get the image above as an example. We have two food stalls such as noodles and hotdogs. There are two customer types such as adults and kids. The adult orders the big-size of food and the kid orders the small-size of food.