Sunday, April 29, 2012

Structural Design Pattern – Facade


Facade Design Pattern:

Façade pattern simplifies the interaction between complex subsystems, by providing a single interface for interacting with those subsystems. As a result the client has to interact with the single subsystem instead of interacting with those individual subsystems. In other words façade is a way to hiding a complex system inside a simpler interface. It has the following parts:
-          Facade – It is the class which actually provides a simplified interface to the complex subsystem.
-          Complex Subsystems – These are the complex subsystems which is required by the client and which is accessible indirectly from the Façade class.
Let’s look at an example.
  1. Complex Subsystem – Contains of the classes which are independent and complex in nature. The client needs access to the all these functionality for a common task/activitity. Without façade the client would need to have knowledge about all functionalities of each of these classes.
public class Class1
    {
        public void Method1()
        {
            Console.WriteLine(“Class1.Method1()”);
        }
    }
    public class Class2
    {
        public void Method2()
        {
            Console.WriteLine(“Class2.Method2()”);
        }
    }
    public class Class3
    {
        public void Method3()
        {
            Console.WriteLine(“Class3.Method3()”);
        }
    }
2. Facade – You can see how the façade class hides all the complexities of the subsystems(class1, class2 and class3) and makes it accessible to the client through a simplified interface i.e. through MainMethod().
public class FacadePattern
    {
        Class1 c1;
        Class2 c2;
        Class3 c3;
        public FacadePattern()
        {
            c1 = new Class1();
            c2 = new Class2();
            c3 = new Class3();
        }
        public void MainMethod()
        {
            Console.WriteLine(“All methods…”);
            c1.Method1();
            c2.Method2();
            c3.Method3();
        }
    }

3. Client – Shows how the façade will be invoked
public static void Main()
        {
            FacadePattern fp = new FacadePattern();
            fp.MainMethod();
      }

No comments:

Post a Comment