Chris's coding blog

C# Design Patterns: the Façade pattern

April 14, 2009

Summary

Access multiple classes in one simple to use class. This class is often static too.

Example

A common use of the Façade pattern is with data access managers, a façade class that contains only static methods for CRUD operations. Another example might be a class that handles payment in an online store. This façade class would link into multiple payment providers (paypal, visa/mastercard) as well as updating any order details in a database table. Rather than making the UI perform 10-20 lines of code, this could be done in a simple CheckoutManager.ProcessPayment(…) method.

public class UserManager
{
// The main implementation of IRepository would be internal to your Core/Domain project,
// so consumers of your API couldn't change the database directlry without going through
// your façade classes.
private IRepository _repository;
public UserManager()
{
_repository = new SqlRepository("some connection string from a config file");
}
public UserManager(IRepository repository)
{
_repository = repository;
}
public User GetById(Guid id)
{
return _repository.ExecuteSql<User>("SELECT * FROM User WHERE Id=@Id", id)
}
public User GetByEmail(string email)
{
return _repository.ExecuteSql<User>("SELECT * FROM User WHERE Email=@Email", email)
}
// more methods User-specific methods.
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharpdesign-patterns

Chris Small

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume