Design Patterns: Difference between revisions
Line 23: | Line 23: | ||
It is in the category of behavioral patterns. | It is in the category of behavioral patterns. | ||
The base class state interface has one or more operation methods. | The base class state interface has one or more operation methods and a context saving the current state and providing a setState() method. | ||
Different derived states can implement operations differently. | Different derived states can implement operations differently. | ||
The context object saves a base class reference to its current state and provides | The context object saves a base class reference to its current state and provides the method to change the current state. | ||
Operations are always called with the context objects current state reference. | |||
The operations can change the current state of the context object as required |
Latest revision as of 14:07, 8 July 2024
Design Patterns
Dispatcher Pattern
- Use a dispatcher if you want to run code in another thread
- A dispatcher has two interfaces: one to add code to execute to a list and one to process the list
- The dispatcher client interface is an invoke() method to schedule code execution in another thread. It just adds the code to a list.
- In the other thread there is a method like invokePending() going through the list and execute the code
- The dispatcher implementation can be a singleton to ensure invoke() and invokePending work with the same list
Singleton
Use if there should be just one object of a class
- create a class with only private constructor(s)
- users of the object can get it with a static get() interface method from the class
- the get method first checks if the object already exists. If not, it creates it with a private constructor and saves it e.g. as a private pointer. Finally it returns the saved object
State Pattern
Use it for context dependent objects that change behaviour depending on internal state. E.g. a switch that acts differently on toggle() if the light is on or off. The pattern makes sure that new states don't affect the objects behaviour of existing states. It is in the category of behavioral patterns.
The base class state interface has one or more operation methods and a context saving the current state and providing a setState() method. Different derived states can implement operations differently. The context object saves a base class reference to its current state and provides the method to change the current state. Operations are always called with the context objects current state reference. The operations can change the current state of the context object as required