Facade Pattern

Introduction and Implementation of Facade Pattern


Category: Design Patterns Tags: C#


Introduction

        Facade design pattern is a Structural Design Pattern which provides a simplified interface over large system sub classes. It hides the complexity and provides what might client need to interact a big class library.

Implementation

        Let’s suppose we need to get required hardware to assemble a computer so for we would be having a large class library where every hardware would be having its specific class:

class MotherBoard
{
    public void GetMotherBoard()
    {
        Console.WriteLine("Getting MotherBoard");
    }
}

class Processor
{
    public void GetProcessor()
    {
        Console.WriteLine("Getting Processor");
    }
}

class RAM
{
    public void GetRAM()
    {
        Console.WriteLine("Getting RAM");
    }
}

class HardDisk
{
    public void GetHardDisk()
    {
        Console.WriteLine("Getting HardDisk");
    }
}

But we can’t create objects of everything every time and we don’t know what and all we have to get so we will be having a facade class which will provide one method we need and it will hide other complexities:

class ComputerFacade
{
    private readonly MotherBoard motherBoard;
    private readonly Processor processor;
    private readonly RAM ram;
    private readonly HardDisk hardDisk;

    public ComputerFacade()
    {
        motherBoard = new MotherBoard();
        processor = new Processor();
        ram = new RAM();
        hardDisk = new HardDisk();
    }

    public void GetRequiredHardware()
    {
        motherBoard.GetMotherBoard();
        processor.GetProcessor();
        ram.GetRAM();
        hardDisk.GetHardDisk();
    }
}

As above class does all initialization of objects and client doesn’t know about all, client will just access the method GetRequiredHardware like:

ComputerFacade facade = new ComputerFacade();
facade.GetRequiredHardware();

And output will be:

 

Getting MotherBoard

Getting Processor

Getting RAM

Getting HardDisk

 


Like 0 People
Last modified on 15 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 126
Questions: 9
Given Best Solutions: 8 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x