Design Patterns – The Facade Pattern
What Is The Facade Pattern
The facade pattern is a higher level interface that simplifies and brings together multiple interfaces of a subsystem. What this means is if you want to do something but that requires interacting with multiple subsystems you can create a facade that same only a few methods that handle all the interaction with the subsystem.
Our Application Requirements
In our city dog registration application lets assume there are a few things that need to be done when a new dog is registered. First the new dog and it’s owners must be entered into the system. Next the registration fee must be processed. Finally, we want the system to send the owners the welcome email.
This is a very simple example but this action requires 3 separate systems to do something in order to complete this one task of registering a new dog.
Using The Facade Pattern
For the sake of simplicity and not cluttering this post with too much code, I am not going to provide code for the sub systems, just the facade.
public class RegistrationManager : IRegister { private IAccountingService _accounting; private IMessageService _messaging; private IRepository = _repository;
public RegistrationManager(IAccountService accounting, IMessagingService messaging, IRepository repository) { _accounting = accounting; _messaging = messaging; _repository = repository; }
public void RegisterDog(IDog dog) { _repository.AddDog(dog); _accounting.ProcessPayment(dog.PaymentOrder); _messaging.SendWelcome(dog.Owners.Find(x => x.PrimaryContact)) } }
As you can see this is a very simple example but it illustrates the concept of the pattern. We have taken 3 tasks, each belonging to a different sub system, and combined them into 1 task in a facade class, in this case the RegistrationManager class.
The RegisterDog method adds the new dog to the repository, sends the payment order to the accounting system, and sends a welcome message to the dogs owners that are flagged as primary contacts.
Summing It Up
I hope this post helps you understand the Facade pattern and I hope you are continuing to learn and have fun with this series.
Be sure to grab the RSS feed or follow me on Twitter to stay up to date and not miss any posts.
The C# Design Patterns Series
Part 2 – The Decorator Pattern
Part 3 – The Abstract Factory Pattern
2 Responses to “C# Design Patterns – The Facade Pattern”
- HardCode Says:
I just starting to use this pattern with the same goals in mind. It’s good to see it here, confirming my suspicions of how the facade works. Thanks.
- BigJim Says:
Hey, thanks much for this excellent series. I look forward to future posts on the various patterns. One thing that is confusing to me, I get this pattern and the “command” pattern mixed up. So when you get to the command pattern, maybe you could contrast it with the facade and explain which tasks each is best suited for.
But thanks again!