05 Dec 2023



Advanced

The Facade design pattern is a structural pattern that provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to use. In C#, the Facade pattern typically involves the following main components:

  1. Facade:

    • Provides a simplified, high-level interface to a set of interfaces in the subsystem.
    • Manages the communication and coordination of the subsystem components.
    public class Facade
    {
        private SubsystemA subsystemA;
        private SubsystemB subsystemB;
        private SubsystemC subsystemC;
    
        public Facade()
        {
            subsystemA = new SubsystemA();
            subsystemB = new SubsystemB();
            subsystemC = new SubsystemC();
        }
    
        public void Operation()
        {
            Console.WriteLine("Facade Operation:");
            subsystemA.OperationA();
            subsystemB.OperationB();
            subsystemC.OperationC();
        }
    }
    
  2. Subsystem Classes:

    • Classes that represent the subsystem and provide specific functionality.
    • Can be complex and have their own methods and interactions.
    public class SubsystemA
    {
        public void OperationA()
        {
            Console.WriteLine("SubsystemA Operation");
        }
    }
    
    public class SubsystemB
    {
        public void OperationB()
        {
            Console.WriteLine("SubsystemB Operation");
        }
    }
    
    public class SubsystemC
    {
        public void OperationC()
        {
            Console.WriteLine("SubsystemC Operation");
        }
    }
    
  3. Client:

    • Uses the facade to interact with the subsystem.
    • Isn't required to know the details of the subsystem's internal structure.
    class Client
    {
        static void Main()
        {
            Facade facade = new Facade();
            facade.Operation();
        }
    }
    

In this example:

  • Facade is the class that provides a simplified interface to the subsystem. It manages the interactions with SubsystemA, SubsystemB, and SubsystemC.
  • SubsystemA, SubsystemB, and SubsystemC are classes that represent different components of the subsystem. They have their own specific functionality.
  • The Client uses the Facade to perform a high-level operation, without needing to interact directly with the individual subsystem components.

The Facade pattern is useful when you want to provide a simple and unified interface to a complex subsystem or set of interfaces. It promotes loose coupling between clients and subsystem components by encapsulating the complexity behind a single entry point.

software-design-patterns
facade-design-pattern
c#