Design Patterns: Difference between revisions

From JoBaPedia
Jump to navigation Jump to search
(Created page with "= 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 implementa...")
 
Line 17: Line 17:


== State Pattern ==
== State Pattern ==
Use it for objects that change behaviour depending on internal state.
E.g. a switch that acts differently on toggle() if the light is on or off.
It makes sure that new states don't affect the objects behaviour of existing states.
The base class state interface has some operation() method.
Different derived states can implement operation() differently.
The state context always calls the base state operation() and remembers the currently active derived state

Revision as of 13:43, 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 objects that change behaviour depending on internal state. E.g. a switch that acts differently on toggle() if the light is on or off. It makes sure that new states don't affect the objects behaviour of existing states.

The base class state interface has some operation() method. Different derived states can implement operation() differently.

The state context always calls the base state operation() and remembers the currently active derived state