C# Facade Design Pattern

5964294206_8e1e34fe28_b

Facade is one of the most popular design patterns, you probably used it in your project without knowing it. This pattern is used to simplify the complex system into one interface. The facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable. You would use it if you have a complex system where the abstractions and the implementations of it are tightly coupled and you would not want the consumer to contact the complex system directly. This pattern involves a single wrapper class which contains a set of members which are required by client. These members access the system on behalf of the facade client and hide the implementation details.

I’ll demonstrate this on an example within a game where player interacts with enemy. Enemy Class contains two sub-classes Move and Speak, this is simplified example of course.

UML diagram:

Facade

 

 

 

 

 

 

 

 

 

 

 

 

 

Lets start with sub-classes. In this example I’m not passing any parameters into Facade.

First lets create Move Subclass that contains two methods each method returns a string.

internal class Move
{
  public string FindPlayer()
  {
     return "Finding player's location ";
  }

  public string MoveToPlayer()
  {
     return "Now I'm moving ";
  }

 internal keyword means that class is accessible from within the current assembly.

Second subclass will be very similar

internal class Speak
{
 public string SpeakToplayer()
 {
    return "Hi! How are You";
 }

 

Now lets implement the Facade Pattern into EnemyFacade Class.

class EnemyFacade
{
  Move a = new Move();
  Speak b = new Speak();

  public void Interact()
  {
    Console.WriteLine(a.FindPlayer());
    Console.WriteLine(a.MoveToPlayer());
    Console.WriteLine(b.SpeakToplayer());
  }

You need to create instances of each subclass in order to call the methods. My methods returns string variable so i can print result straight to the console.

Last part of code will be our client class that  calls the Facade method.

class Program
{
  static void Main(string[] args)
  {
    EnemyFacade facade = new EnemyFacade();

    facade.Interact();
  }

 

I simplified this as much as i could. Idea behind the pattern is very simple. Client calls only one method, and he is not interested in all the methods running in the background. This pattern is extremely useful in larger programs. I hope you will find this useful, in next article you will learn another super useful structural design pattern called Adapter. Stay Awesome!