Behavioral Design Patterns
Ibrahim AdDandan
Visitor Design Pattern
- What is the visitor design pattern?
- Why is it useful?
- When to use it?
Visitor
Problem
Problem
- Imagine you have a hierarchy of classes representing different types of shapes, such as Circle, Square, and Rectangle.
- You want to write a function that calculates the area of each shape.
- One way to do this is to add a separate area() method to each shape class.
- However, this approach is not very flexible. If you want to add a new operation, such as calculating the perimeter of each shape, you would need to add a new method to each shape class.
Solution
- The visitor design pattern provides a more flexible solution.
- The pattern defines a visitor interface that declares methods for each operation that needs to be performed on the elements of the object structure.
- Each concrete visitor class implements these methods and provides the specific behavior for each operation.
- The elements of the object structure implement an accept() method that takes a visitor as a parameter.
- When an element is visited, it calls the corresponding method on the visitor object.
Benefits
Benefits
- Flexible: New operations can be added without modifying the existing element classes.
- Decoupled: The element classes are decoupled from the visitor classes. This makes the code more reusable and maintainable.
- Extensible: The visitor design pattern can be used to implement new operations without modifying the existing object structure.
CodeBase Example
CodeBase Example
Fill Target info or
Close workflow todo/ get next... in visa
export to xml
GEO Location set coo or report about location
Observer design pattern
- What is the observer design pattern?
- Why is it useful?
- When to use it?
Observer
Problem
- Imagine you have a weather forecasting application.
- The application needs to update the weather forecast for different cities whenever the weather data changes.
- One way to do this is to poll the weather service for updates at regular intervals.
- However, this approach is inefficient and can waste bandwidth.
Problem
Solution
- The observer design pattern provides a more efficient solution.
- The pattern defines an observer interface that declares a method for updating observers when the state of the subject changes.
- Each concrete observer class implements this method and provides the specific behavior for updating the observer.
- The subject class maintains a list of observers and notifies them whenever its state changes.
Solution
bR as example
Silent notification as example
CODE Base
Example