Facade Pattern is a class (complex system) that contains multiple instances of objects (subsystem) each of these objects has its own methods that perform certain tasks. Inside the complex system class it can have one or more methods that wraps one or more subsystem object methods.
To demonstrate this I will use a Car as an example, building car consist of several process or subsystems to build the parts such as wheels, seats, engines and the body. The main system or complex system is to assemble the car.
Below I have a class called Body, Engine, Seats and Wheels, and each of these class contain a method to add certain parts.
The Body class contains a method called AddBody() which takes a enumerated type of BodyType, the body type can be either a sedan, hatch or a suv.
public class Body { public Body () { } public void AddBody(BodyType bodyType) { Console.WriteLine ("{0} Body Added", Enum.GetName(typeof(BodyType), bodyType)); } }
The Engine class contains a method called AddEngine() which takes an integer value to specify the engine’s cyclinder.
public class Engine { public Engine () { } public void AddEngine(int cyclinders) { Console.WriteLine("{0} Cylinder Engine Added", cyclinders.ToString()); } }
The Seats() class contains a method call AddSeats() which takes an integer value to specify the number of seats that the car need.
public class Seats { public Seats () { } public void AddSeats(int num) { Console.WriteLine("{0} Seats Added", num.ToString()); } }
The Wheels() class contains a method call AddWheels() which takes an integer value to specify the number of wheels that the car need, I know normally a car has 4 wheels, but what the heck we can build a special car with 5 wheels if we want to.
public class Wheels { public Wheels () { } public void AddWheels(int num) { Console.WriteLine("{0} Wheels Added", num.ToString()); } }
Now we have all these subsystems created and to make these individual class to do it’s work we need to create a class called Car() with a method call BuildCar() which will execute each of these subsystem methods.
public void BuildCar() { Console.WriteLine ("Building a car."); body.AddBody(BodyType.Sedan); engine.AddEngine(6); seats.AddSeats(4); wheels.AddWheels(4); Console.WriteLine("Car is complete."); }
In our Main() method we can instantiate the Car object and call the BuildCar() method.
public static void Main (string[] args) { var car = new Car(); car.BuildCar(); }
Source Code:
- GitHub Repository – Design Patterns. Full source code for this post can be pulled from my GitHub repository.
Reference: