Open In App

Design Patterns in Object-Oriented Programming (OOP)

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Software Development is like putting together a puzzle. Object-oriented programming (OOP) is a popular way to build complex software, but it can be tricky when you face the same design problems repeatedly. That’s where design patterns come in.

Design patterns are like well-known recipes for common problems in software development. They’re not step-by-step instructions, but more like guidelines to help you solve these problems in a flexible and efficient way. These patterns gather the wisdom of the software development community, making it easier for developers to work together and create software that’s easy to maintain, adapt, and reuse.

Singleton Pattern

The Singleton Pattern is a design pattern in object-oriented programming that ensures a class has only one instance and provides a global point of access to that instance. This means that regardless of how many times the class is instantiated, there will always be only one instance, which can be accessed from any part of the program.

Explanation with Real-World Example

Consider a real-world analogy of a government in a country. In this context:

  1. Singleton Class: The government can be represented as a Singleton class. Only one government exists for a particular country.
  2. Instance Creation: When you create a government, you’re essentially creating the one and only instance of that government for the country.
  3. Access Point: To interact with the government, you don’t create a new government every time you need something from it. Instead, you access the existing government. This ensures that the decisions and actions of the government are consistent and centralized.

Factory Method Pattern

The Factory Method Pattern is a creational design pattern in object-oriented programming. It defines an interface for creating an object but lets subclasses alter the type of objects that will be created. It provides an abstract method for creating an object, and the concrete subclasses of the factory class implement this method to produce objects of a specific type.

Explanation with Real-World Example

Consider a real-world example of a vehicle manufacturing company. The company produces different types of vehicles such as cars, motorcycles, and bicycles. In this context

  1. Factory Class: The vehicle manufacturing company can be seen as the factory class, which defines an abstract method.
  2. Concrete Factories: There will be multiple concrete factory classes, each responsible for creating a specific type of vehicle. For example, CarFactory, MotorcycleFacotry and BicycleFactory.
  3. Products: The products are the vehicles themselves- cars, motorcycles, or bicycles.

The Factory Method Pattern is used in software development when you need to decouple the object creation from the object’s usage.

Abstract Factory Method Pattern

The Abstract Factory Pattern is a creational design pattern in object-oriented programming that provies an interface for creating families of related or dependent objects without specifying their concrete classes. It’s a higher-level pattern compared to the Factory Method Pattern, where you have not just one factory but a family of factories that work together to create related objects.

Explanation with Real World Example

Let’s consider a real-world example of a furniture manufacturer. This manufacturer produces various types of furniture sets, such as modern and vintage sets. Each set consists of several pieces of furniture, including a table, chiars, and a sofa. In this context:

  1. Abstract Factory: The abstract factory represents the furniture factory, which defines methods for creating different types of furniture products.
  2. Concrete Factories: There are two concrete factories – ModernFurnitureFactory and VintageFurnitureFactory. Each of these factoreis creates a complete set of furniture in a consistent style.
  3. Product Families: The product families are the sets of furniture (e.g., modern or vintage) with individual objects (e.g., table, chairs, sofa).

The Abstract Factory Pattern is used when you need to ensure that the created objects are compatible and belong to a consistent family.

Builder Pattern

The Builder Pattern is a creational desing pattern in object-oriented prgramming that is used to construct a complex obect step by step. It separates the construction of a complex object from its representation, allowing the same construction process to create different representations of an object. It is particularly used when an object has a large number of parameters, some of which are optional, and it provides a more readable and maintainable way to create objects with different configurations.

Explanation with Real World Example

Imagien a real-world scenario of building a custom computeer. When ordering a custom computer, you have various components to choose from, such as the processor, memory, storage, graphics card, and so on. This customization process can be represented using the Builder Pattern:

  1. Director Pattern: In this case, the computer seller acts as the director. They understand the configuration options and guide you through the customization process.
  2. Builder: The builder is responsible for constructing the computer step by steo. It takes your choices for each component and assembles the computer accordingly.
  3. Product: The end result is your custiom-build computer, which can have various configurations based on your device.

The Builder Pattern is used in situations where you need to create complexo objects with multiple configuration options, especially when some of these optins are optional or can have default values.

Adapter Pattern

The Adapter Pattern is a structural design pattern in object-oriented programming that allows objects with incompatilbe interfaces to work together. It acts as a bridge between two incompatible interfaces, making them compatible without changing acutal classes. The Adapter Pattern involves a single class called the adapter that is responsible for joining functionalities from independent or incompatible interfaces.

Explanation with Real World Example

Let’s consider a real-world scenario involving electrical outlets. In different countries, you often find different types of electrical outlets and plugs. For instance the United States uses Type A and Type B outlets with flat pins, while Europe uses Type C and Type F outlets with round pins. If you have an appliance with a U.S. plug and want to use it in Europe, you’ll need an adapter:

  1. Clinet: The appliance (e.g., a laptio charger) is the client, designed for a U.S. outlet.
  2. Target Interface: The European outlet is the target interface. It’s what the client needs to connect to.
  3. Adapter: The adpater, in this case, is the physical device that converts the U.S. plug to the European outlet.

The Adapter Pattern is used when you want to make two incompatible interfaces work together.

Proxy Pattern

The Proxy Pattern is a structural design pattern in object-oriented programming. It provides a surrogate or placeholder for another object to control access to it. In other words, a proxy acts as an intermediary or representative for an object, allowing you to add extra funtionality, such as lazy loading, access control, or caching, without altering the underlying object.

Explanation with Real World Example

Consider a real-world example of a proxy in the context of a smart card access system:

  1. Real Object: The real object in this scenario is the physical access control system, which authenticates users and grants or denies access based on their credentials.
  2. Proxy: The proxy, in this case, is a security guard who stands between users and the access control system. The security guard check user credentials, verify identities, and decide whether to grant access. Users interact with the security guard rather than the access control system.
  3. Client: Users who want to enter a secure area. Instead of interacting directly with the access control system, they interact with the security guard (proxy).

The security guard (proxy) can provide additional services, such as logging access, verifying IDs, or controlling the flow of people, without the users (client) needing to be aware of these operations. This is analogous to how a proxy in software provide caching, lazy loading, or access control without affecting the underlying object.

The Proxy Pattern is used in various scenarios where you want to control access to an object or add additional functionality without changing the object’s code.

Decorator Pattern

The Decorator Pattern is a structural desing pattern in object-oriented programming. It allows you to dynamically add new behavior or responsibilities to objects without altering their code. This pattern is acheived by creating a set of decorator classes that are used to wrap the original object. Each decorator addis its own functionality while delegating the rest of the work to the wrapped object.

Explantion with Real World Example

Imagine you are ordering a coffee from a cafe. You can choose a base coffee, such as espresso, and then add various toppings to enhance the coffee. Each topping adds a specific flavor or characteristic to the baes coffeee without changing the coffee itself. In this context:

  1. Component: The base coffee, such as espresso, represents the core component that you want to enhance.
  2. Concrete Component: Espresso is a concrete component, as it’s the initial coffee you start with.
  3. Decorator: The toppings like caramel, whipped cream, or cinnamon represent decorators. They add extra flavor or features to the core coffee.
  4. Concrete Decorator: Each topping is a concrete decorator that extends the base coffee with specific features.

The Decorator Pattern is used in situations where you need to add responsibilities or behaviors to objects dynamically and without altering their underlying class.

Composite Pattern

The Composite Pattern is a structural design pattern in object-oriented programming that allows you to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly. In other words, you can work with individual objects and their collections in a consistent way, abstracting away the differences between them.

Explanation with Real World Example

In a file system, you have a hierarchical structure with directories (composites) containing files (leaves). This structure can be effectively modeled using the Composite Pattern:

  1. Component: The component represehts the common interface for all file system elements.
  2. Leaf (File): A leaf is a concrete file, which cannot have child elements.
  3. Composite (Directory): A composite is a directory that can contain child elments, including other directories and files.

Here’s how this example works:

  • Client Code: When you want to work with the file system, you don’t need to differentiate between individual files and directoreis. You can treat all elements uniformly.
  • Tree Structure: The components, whether leaf of compsite, are organized in a tree structure to represent the file system’s hierarchical nature.

Observer Pattern

The Observer Pattern is a behavioral desing pattern in object-oriented programming. It defiens a one-to-many dependency between objects so that when one object (the subject) changes its state, all its dependents (observers) are notified and updated automatically. In other words, the observer pattern allows one object to inform a list of other objects about changes without knowing who or what those objects are.

Explantion with Real World Example

Think of a real-world scenario of a news agency and its subscribers:

  1. Subject (News Ajency): The news agency is the subject. It generates news and broadcasts it.
  2. Observer (Subscribers): Subscribers are the observers. They subscribe to the news agency to receive updates.
  3. Update Mechanism: When the news agency publishes a new article or breaking news, all subscribers receive the updates without the news agency knowing who they are or how many there are.

This real-wrold analogy demonstrates how the observer patten works. The news agenchy (subject) informs its subscribers (observers) about changes without needing to be aware of the specific subscribers.

The Observer Pattern is used in various scenarios where a one-to-many relationship exists between objects, and one subject needs to notify multiple others about changes.

Strategy Pattern

The Strategy Pattern is a behafvioral design pattern in object-oriented programming. It defines a family of algorithms, encapsulates each one, and makes them interchangeable. The pattern allows a client to choose and use an algorithm from a family of algorithms at runtime. It separates the algorithm from the client, making the algorithm’s implementation details hidden from the detail.

Explanation with Real World Example

Let’s consider a real-world example involving a navigation application that provides various routing options to users:

  1. Context (Navigation Application): The navigation applications is the context that requires different routing algorithms. It represents the client.
  2. Strategy (Routing Algorithms): The routing algorithms are the strategies. They encapsulate various methods to calculates notes, such as Shortest Route, Scenic Route and Avoid Traffic Route.
  3. Client’s Choice: The user of the navigation application can choose the routing strategy they prefer. For example, if they select Avoid Traffic Routhe the application employs that specific routing algorithm.

This real world example illustrates how the Strategy Pattern allows users to select a specific routing algorithm without needing to understand the inner workings of the algorithm or the application.

The Strategy Pattern is used in situations where multiple algorithms or strategies are available for a specific task, and you want to select and use one of them at runtime.

Command Pattern

The Command Pattern is a behaviroal desing pattern in object-oriented programming that encapsulats a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations. It turns a request into a standalone object with its own class, parameters, and methods to invoke the request. This pattern decouples the sender and receiver of a request. allowing for the sender to issue requests without needing to know the specific operations or the receiver’s class.

Explanation with Real World Example

Let’s consider a real-world scenario involving a remote control for a television:

  1. Command: In this context, a command is a representation of a specific operation, like turning the TV on, changing the channel, or adjusting the volume. Each command is encapsulated as an object with a defined method.
  2. Invoker (Remote Control): The remote control is the invoker. It holds a list of commands and can execute them without needing to know the details of the TV’s internal workings.
  3. Receiver (TV): The television is the receiver. It understandsthe individual commands, such as how to turn on or change channels. The commands act as intermediaries to invoke the appropriate methods on the receiver.

In this example, the Command Pattern allows the remote control (invoker) to issue various commands to the TV (receiver) without requiring a deep understanding of the TV’s internal operations. The remote control interacts with commands that encapsualte specific actions, providing a more flexible and decoupled way to control the TV.

The Command Pattern is used in various scenarios where you want to encapsulate requests as objects and decouple the sender and receiver of the requests.

State Pattern

The State Pattern is a behavioral desing pattern in object-oriented programing. It allows one object to alter its behavior when its internal state changes. The pattern acheives this by representing each state as an object and delegating the state-specific behavior to these state objects. The context (the object that uses the state) holds a reference to the curreent state object and delegates operations to it.

Explanation with Real World Example

Let’s consider a real-world example involving a vending machine, which can have different states based on its current condition:

  1. Context (Vending Machine): The vending machine represnts the context. It can be in different states like idle, payment in progress, and item dispensed. The context is responsible for maintaining the current state and delegating actions accordingly.
  2. State (State of Vending Machine): Each state is represented as on object (e.g., idle state, payment in progress state, item dispensed state). These state objects encapsulate the behavior associated with that particular state.
  3. Transition: When a user interacts with the vending machine (e.g., inserts money or select an item), the context switches from one state to another. Each state knows how to handle actions specific to that state.

In this example, the State Pattern allows the vending machine to change its behavior based on its current state without using a complex conditional structure. It simplifies the code, making it more modular and maintainable.

The State Pattern is used in scenarios where object can exist in multiple states, and the behavior of the object must change dynamically based on its state.

Template Method Pattern

The Template Method Pattern is a behavioral desing pattern in object-oriented programming. It defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It allows subclasses to redefine certain steps of an algorithm wihout altering the algorithm’s structure. This pattern promotes reusability by providing a common structure for a family of related algorithms.

Explanation with Real-World Example

Let’s consider a real-world example involving the prepartaion of a hot beverage such as coffee or tea:

  1. Template Method (Beverage Recipe): The template method represents the common structure of making a hot beverage. It outlines the algorithm, including steps like boiling water, brewing the beverage, and serving it. Some steps are defined in the template method, while others are left as abstract methods to be implemented by concrete subclasses.
  2. Concrete Sublclasses (Coffee, Tea): Concrete subclasses represent specific beverages (e.g., Coffee, Tea). They inherit the common structure from the template method but provide their own implementation for steps like brewing. For example, Coffee and Tea will have different methods for brewing coffee and tea, respectively.
  3. Hook Methods: The template method may include hook methods, which are methods with default implementation that can be overridden by concrete subclasses. For example, a hook method can allow the addition of sugar or milk, which is optional and may vary between beverages.

In this example, the Template Method Pattern provides a common structure for making hot beverages, but it allows individual beverages to customize specific steps while preserving the overall algorithm.

The Template Method Pattern is used in scenarios where you want to define the outline of an algorithm and allows subclasses to provide specific implementations for certain steps.

Visitor Pattern

The Visitor Pattern is a behavioral design pattern in object-oriented programming that allows you to add further operations to objects without having to modify them. It i used when you have a set of objects with different types, and you want to perfrom a common operation on them without modifying their classes. The pattern achieves this by defining a separate visitor class or interface, which is responsible for performing operations on these objecs. Each object accepts the visitor and delegates the operation to it.

Explanation with Real World Example

Consider a real-world example of a tax calculation system in a finance application:

  1. Elements (Taxable Items): The elements are different taxable items such as products, services, and investments. Each taxable item is a distinct class with its properties and methods.
  2. Visitor (Tax Calculator): The visitor, in this case is the tax calculator. It’s a separate class or set of classes responsible for performing tax calculations on various taxable items.
  3. Operation (Tax Calculation): The operation is the tax calculation itself. It’s a specific operation that needs to be performed on each taxable item. The tax calculator class defines methods for different types of taxable items to calculate taxes.

In this example the Visitor Pattern allows you to add new tax calculation functionality to your finance application without modifying the existing classes of taxable items. Each taxable item can accept the tax calculator (visitor) and delegate the tax calculation operation on it.

The Visitor Pattern used in situations where you have a set of objects with different types or classes and you want to perform a common operation on all of them.

Memento Pattern

The Memento Pattern is a behavioral desing pattern in object-oriented programmming that provides a way to capture and externalize an object’s interal state without violating its encapsulation. It allows an object to capture its current state in a memenot object, which can later be used to restore the object to that state. The pattern is particularly useful when you need to implement undo/redo functionality or save and restore an object’s state.

Explanation with Real World Example

Consider a real-world example involving a text editor:

  1. Originator (Text Editor): The originator is the text editor. It’s the object whose state you want to save and restore. The text editor has a current document with text.
  2. Memento (Snapshot): The memento represents a snapshot of the text editor’s state. It captures the content of the current document.
  3. Caretaker (History Manager): The caretaker, in this case, is the history manager. It keeps a stack of mementos (snapshots) taken at various points in the text editor’s history.

In this scenario, the Memento Pattern allows the text editor to save its state by creating a memnto object (snapshot) and pushing it onto the history manager’s stack. Later, if the users wants to undo an action, the history manager can pop the latest memento from the stack and use it to restore the text editor’s state to a previous point in time.

Conclusion

Desing pattern in object-oriented programming are like blueprints for solving common problems. By understanding and using these patterns, developers can write more maintainable, scalable, and efficient code. Whether you’re creating a complex GUI, managing database connection, or designing a game, there’s a design pattern that can help you build better software. So, keep these patterns in mind as valuable tools for your programming journey. Happy Coding!



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads