Common Behavioral Patterns (part 2/3)

dieutb
3 min readApr 13, 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.

Command, Iterator, Memento

1. Command

Command Pattern
  • We apply this pattern when
    - We want to separate the UI and the business logic to prevent duplicated methods.
    - We want to pass a method as a parameter of another method.
    - It also helps to implement undo, log, transaction, and the callback (inside the execute method of the invoker class)
  • In ruby, the comment layer and receiver layer have been removed when we using block, lambda, proc.
  • This pattern would have
    - Invoker receives the command request from the client. Invoker stores a command as a private variable and Invoker would have a public execute method.
    - Command is the middle layer. The execution method of this class would contain the receiver execution method.
    - Receiver contains the main behavior logic.
  • For example, an editor with several buttons. By default, we implement an interface Button and there are many subclasses. It could happen a problem when we change some logic in the base class. Furthermore, some of them such as Ok, Save, and Yes have the same logic “save”. It would be duplicated code if we define the “save” function on each subclass. So, by splitting out the logic and we can reuse the code.
  • Let's take an example, an editor has 3 buttons “copy”, “cut”, “paste”

2. Iterator

  • This pattern aims to control collections’ data (array, hash, tree) and behavior by splitting the iterator into a separate class for easy reuse and extensibility.
Iterator
  • For example, we have CircleShape and SquareShape. These shapes are different structures and behaviors from each other. The CircleShape’s node can move around, but the SquareShape’s node can not.

3. Memento

Memento
  • This pattern is about capturing the history of an object. It let us save and restore the previous state of an object without revealing the details of its implementation.
  • In this pattern, we would have 3 objects such as
    - Originator is the one that would be captured states. Every moment it only has a state.
    - Memento is the recipe for how we store the state of Originator. We can count memento as a revision of Originator.
    - CareTaker, like its name, would hold and take care of the Originator and Mementos
  • Let's get an example, we would like to log all the historical changes of the campaign.

References

--

--

dieutb
dieutb

Written by 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 :)

No responses yet