Thursday, February 27, 2014

FACADE DESIGN PATTERN

According to GoF’s definition, facade pattern is :
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
real world example :
In this example we need to start computer. Computer class acts as facade which encapsulates other complex classes represented by: HardDrive class, Memory class and CPU class. Each of this classes has operations which must be performed when Start() method of Computer class is called.
public class Computer
{
private readonly CPU _cpu;
private readonly HardDrive _hardDrive;
private readonly Memory _memory;

private const long BootAddress = 1;
private const long BootSector = 1;
private const int SectorSize = 10;

public Computer()
{
_cpu = new CPU();
_hardDrive = new HardDrive();
_memory = new Memory();
}

public void Start()
{
_cpu.Freeze();
_memory.Load(BootAddress, _hardDrive.Read(BootSector, SectorSize));
_cpu.Jump(BootAddress);
_cpu.Execute();
}
}

public class CPU
{
public void Freeze()
{
Console.WriteLine("CPU is frozen");
}

public void Jump(long position)
{
Console.WriteLine("Jumping to position: {0}", position);
}

public void Execute()
{
Console.WriteLine("Executing...");
}
}

public class HardDrive
{

public byte[] Read(long lba, int size)
{
var bytes = new byte[size];
var random = new Random();
random.NextBytes(bytes);
return bytes;
}
}

public class Memory
{
public void Load(long position, byte[] data)
{
Console.WriteLine("Loading data: ");
foreach (var b in data)
{
Console.Write(b+ " ");
Thread.Sleep(1000);
}

Console.WriteLine("\nLoading compleded");
}
}

class Program
{
static void Main()
{
var computer = new Computer();
computer.Start();
}
}
Real Example Using Car  -


class CarModel
{
public void SetModel()
{
Console.WriteLine(" CarModel - SetModel");
}
}
class CarEngine
{
public void SetEngine()
{
Console.WriteLine(" CarEngine - SetEngine");
}
}
class CarBody
{
public void SetBody()
{
Console.WriteLine(" CarBody - SetBody");
}
}
class CarAccessories
{
public void SetAccessories()
{
Console.WriteLine(" CarAccessories - SetAccessories");
}
}
public class CarFacade
{
CarModel model;
CarEngine engine;
CarBody body;
CarAccessories accessories;

public CarFacade()
{
model = new CarModel();
engine = new CarEngine();
body = new CarBody();
accessories = new CarAccessories();
}

public void CreateCompleteCar()
{
Console.WriteLine("******** Creating a Car **********\n");
model.SetModel();
engine.SetEngine();
body.SetBody();
accessories.SetAccessories();

Console.WriteLine("\n******** Car creation complete **********");
}
}
class Program
{
static void Main(string[] args)
{
CarFacade facade = new CarFacade();
facade.CreateCompleteCar();
Console.ReadKey();
}
}



No comments:

Post a Comment