Facade Design Pattern In C# With Examples

What is the Facade Design Pattern in C#?

The Facade Design Pattern dictates the necessity of presenting a unified interface to a set of interfaces in a subsystem, as defined by the Gang of Four (GOF). This pattern simplifies the utilization of the subsystem through a more accessible interface at a higher level.

A design pattern known as the Facade Design provides a simplified front-end for a complex system comprised of classes, libraries, or frameworks. The primary goal of the facade pattern is to offer a streamlined and clear interface to external users, while delegating the detailed tasks to the appropriate classes within the system. By acting as a wrapper for a set of subsystems, the Facade class facilitates seamless communication among them.

The facade represents the exterior of a building, as its name suggests. Imagine constructing a single building. The only components visible to passersby are the glass panels and walls. The interior design, plumbing, electrical work, and other complex elements remain hidden from public view. Essentially, the facade offers an inviting appearance to observers outside the building while keeping all intricate aspects concealed.

Recognizing the C# Facade Design Pattern with a Single Real-Time Example

Identify Complex Subsystems: Begin by identifying the challenging elements within your system that necessitate streamlining. These could include elaborate systems or frameworks containing multiple interconnected classes.

Develop a Facade Class: Create a facade class that provides a simple interface to the complex subsystems.

Assigning Calls to Subsystems: The requests from the client should be allocated by the facade to the appropriate subsystem entities. The facade is responsible for handling all intricacies and interdependencies of the subsystems.

By leveraging the facade pattern to interact with the system, clients can seamlessly access and utilize the complex subsystems.

Let's explore a practical scenario to better understand the C# Facade Design Pattern.

To aid in comprehension, please refer to the provided visual representation. In this scenario, our task involves developing a program for facilitating online purchases through an electronic commerce system.

The CSS code snippet below demonstrates the styling for a placeholder diagram:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

When observing the image provided, it is essential for the client to initiate an instance of the Product class initially and then invoke the GetProductDetails method to retrieve the necessary product information for placing an order.

Then, it is necessary to proceed with the payment once all details are confirmed, specifically when the product is available. The customer is required to invoke the MakePayment function and instantiate the Payment class to facilitate this process. Additionally, the customer needs to generate an instance of the invoice class and invoke the SendInvoice function to dispatch the invoice to the customer following a successful payment transaction. Consequently, the customer must diligently follow the aforementioned steps sequentially to finalize the order.

In C#, the Facade Design Pattern includes an extra class positioned above the existing classes. It is occasionally known as a Wrapper class or Facade Class.

The <style> element includes a CSS code snippet that defines a placeholder diagram. This diagram has a background styled with a linear gradient, a border radius of 12 pixels, padding of 40 pixels, a margin of 20 pixels on the top and bottom, and is centered within its container. Additionally, it contains a placeholder icon with a font size of 3rem and a bottom margin of 10 pixels, as well as placeholder text styled with a color of #9ca3af and a font size of 1rem.

Therefore, in this scenario, the additional class order handles the responsibility of sequencing the Facade class. This class orchestrates the execution of methods in a predefined sequence and instantiates an object of every class internally. When initiating an order, the client will invoke the PlaceOrder method of the Order Class instead of directly interacting with individual classes and their methods. Internally, the PlaceOrder function will utilize the Product, Payment, and Invoice classes to finalize the order.

NOTE: It's important to keep in mind that the Facade Design Pattern helps to relocate undesired dependencies to one location while also reducing the overall complexity of the program.

Understanding the Class or UML Diagram of Facade Design Pattern:

Let's explore the various components of the Facade Design Pattern and the class diagram (also referred to as the UML diagram). To understand the class diagram associated with the Facade Design Pattern, please consult the following illustration.

The given CSS code snippet demonstrates the styling for a placeholder element. The diagram showcases a background with a linear gradient color scheme, rounded corners, padding, margin, and center alignment. Additionally, it includes an icon with specified dimensions and text in a distinct color and size.

The Facade Design Pattern comprises of three classes, as depicted in the diagram above. These are presented in the following sequence:

  • Responsibilities of the Facade Class include directing client requests to the appropriate subsystem objects based on the specific subsystem classes responsible for each request.
  • The Subsystem Classes execute the designated tasks assigned to them without any knowledge of the Facade class.
  • NOTE: Despite not being aware of it, we have unintentionally applied the Facade Design Pattern extensively in our projects. You are utilizing Facade Design Patterns if you are working on Web APIs. When it comes to real-time applications, this is one of the best design patterns. Understanding the Facade Design Pattern will help you create a better project architecture.

    Implementing Facade Design Pattern in C#:

Let's utilize C# to demonstrate the discussed example in a systematic manner.

Step 1: CreatingSubsystems

The Product, Payment, and Invoice classes are designated as the Subsystem classes in our illustration; each individual class will be accountable for specific duties. Therefore, we will create the aforementioned classes and allocate their respective responsibilities.

After verifying product availability, it is essential to proceed with the payment process. The Payment Subsystem plays a crucial role in facilitating this transaction. Therefore, it is necessary to transfer the provided code snippet into a class file named Payment.cs. Within this class, the validation of the customer's chosen payment method is imperative. Whether it is through Net Banking, UPI, or Cash on Delivery, the system must execute the suitable payment method accordingly.

Invoice System: Following a payment confirmation, it is essential to provide customers with an invoice for the transaction. Therefore, please insert the provided code snippet into a new class file named Invoice.cs. To dispatch the invoice, implement the SendInvoice method within this class. Additionally, there may be instances where a Payment Failed Invoice needs to be sent to the client. The Invoice class can handle requests from either the Facade class or directly from the client.

NOTE: Other than printing the specifics, we have yet to really implement the techniques in this case. Our goal is to comprehend the C# implementation of the Facade Design Pattern rather than concentrate on the actual method implementations.

Step 2: Creating the Facade Class

It operates in a comparable manner to a wrapping class. Therefore, please duplicate and insert the provided code below into a class file named Order.cs. Within this class, a particular method will instantiate objects of the subclass and invoke the relevant methods sequentially to initiate an order. This class offers clients a simple interface to place orders effortlessly.

By leveraging the Facade class, we can effectively hide the complexity associated with creating multiple subclass instances and calling their respective methods. In essence, this class acts as a protective layer for the subclasses. The PlaceOrder function takes care of the entire order placement process.

Step 3: Client

The </style> is the sole class that will make use of the Facade class. It is going to serve as the Main method for the Programme class in this scenario. Therefore, please implement the specified adjustments to the Main method of the Programme class.

Advantages of the Facade Design Pattern

  • Simplified Interface: Provides a single, more user-friendly interface for the intricate subsystems, hence simplifying their use.
  • Isolation: A certain amount of isolation from the intricate subsystems is provided by isolation, which is advantageous in situations where subsystem changes often.
  • Better Testability and Maintainability: By concentrating on system interfaces and reducing interdependencies, Facade can streamline the testing process.
  • Real-Time Applications:

The following situations are where the Facade Design Pattern comes in handy:

  • Simplifying Complex Systems: You should offer a straightforward interface to complex systems or frameworks that consist of several interconnected classes or layers. The Facade design can conceal this intricacy beneath a uniform, basic interface.
  • Decoupling Systems: By concealing the underlying intricacies of the client, a facade can offer loose coupling in a system where the components are closely coupled or interdependent.
  • Layered Architecture: Multi-layered architecture can have a facade that serves as the entrance to every stratum.
  • Enhanced Readability and Usability: When a system's readability and usability are your goals. It can be simpler for other developers to comprehend and utilize a complex subsystem when it has a clear and uncomplicated interface, such as a facade.
  • Reducing Dependencies: This approach lessens the reliance of external code on a library's or framework's internal operations, protecting the client code from upcoming modifications or subsystem complexity.
  • Subsystem Interface Standardisation: Harmonize subsystem interfaces. If each subsystem has distinct interfaces, a fa�ade can provide a consistent interface, making working with them easier.

Utilizing the facade design pattern can enhance the encapsulation, maintainability, and flexibility of your program. It promotes a decoupled architecture, facilitating easier expansion or modification of the subsystem in the future without impacting the clients adversely. In essence, the Facade pattern serves as a valuable asset in managing intricacy and improving the overall structure of object-oriented programming languages like C#.

Conclusion:

In summary, the C# Facade design pattern simplifies interaction with a complex subsystem by providing a unified interface. This allows clients to engage with the subsystem using specific methods without needing to understand its internal operations, as the intricate details are encapsulated within a single facade class.

Input Required

This code uses input(). Please provide values below: