Why do we need design patterns in C?

Design patterns are a general solution to a recurring problem. There are 5 design patterns in C:

Why do we need patterns?

First-Class ADT pattern

The first-class ADT pattern separates the interface of a module from its implementation as shown below:

The first-class ADT pattern is used for:

  • Improving encapsulation by separating interface from implementation.
  • Loose coupling between client and internal data by providing a separate interface for the client.
  • Controlling construction and destruction of objects, ensuring that objects are created in a valid state and are destructed by de-allocating all elements.

State pattern

The state pattern allows an object to change its state when an object needs to alter its behavior, as shown below:

The state pattern is used to:

  • Reduce duplication and complexity by removing conditional statements to alter the state of an object.
  • Encapsulate the internal behavior of each state. This makes it easier to identify and incorporate changes to the states.

Strategy pattern

The strategy pattern allows an object to alter its strategy, i.e., its algorithm or behavior at the run-time, as shown below:

The strategy pattern is used to:

  • Allow the client to modify an object by adding their own code without modifying the existing code. The strategy pattern follows the open-closed principle, as it is open for extension but closed for modification.
  • Reduce complexity by removing conditional statements to alter the behavior of an object.
  • Allow an object to implement different algorithms in different situations.

Observer pattern

The observer pattern notifies the observer objects when a subject object changes its state, as shown below:

The observer pattern is used for:

  • Loose coupling between a subject and its observers, as there is no direct relation between the subject and the observers. They are related through another observer class that acts as an interface of the observers.

Reactor pattern

The reactor pattern handles the concurrent service requests from one or more inputs to a service handler as shown below:

The reactor pattern is used for:

  • Loose coupling between event handlers, as they are encapsulated and separated from each other. The reactor pattern follows the single responsibility principle, as the responsibilities are separated by encapsulating event handlers.

The reactor pattern follows the open-closed principle, as new event handlers can be added without modifying the existing code.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved