Common Behavioral Patterns (part 1/3)

dieutb
3 min readApr 8, 2022
Behavioral Pattern

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.

Chain of Responsibility, State, Strategy, Template Method

1. Chain of Responsibility

Chain of Responsibility
  • This pattern lets us pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.
  • Let’s take a sample of food sharing between a monkey and a pig. They line up and wait for eating. Monkey only can eat the banana and Pig only can eat bran.

2. Template Method

Template Method Pattern
  • This pattern is pretty useful to reduce the unexpected duplicated code when we have objects’ behaviors doing the same things but different a bit in the logic.
  • In order to implement this Pattern, we need to consider which methods could be overridden in sub-classes. It may cause the methods split smaller.
Template Method Pattern

3. State

  • We use this pattern in case we have an object’s behavior changes when its state changes.
  • The context object keeps a state that also keeps the connection to the context.
  • After finishing the behavior, the context’s state is updated inside the state.
State Pattern
  • For example (the code below), we have the order object and it would have behaviors change based on its state. When the order is on OrderStateCard, the order has behavior add_products and behavior checkout. However, when changing to OrderStatePayment, the order only have behavior payment
State Pattern

4. Strategy

Strategy Pattern
  • This pattern is used when an object context has behavior’s LOGIC change when its strategy change. Strategies have some behavior with the same names but different logic.
  • Only the context can update its strategy.
  • Let’s get a sample with the MapDirection. From A to B with different transportation types, the direction would be different.

References

--

--

dieutb

passion in finding solutions and research some things relate to technical and helpful in life. Also strongly interest in foods, travel, and gentle music :)