Definition
Provide a unified interface to a set of interfaces in a subsystem.
Facade defines a higher-level interface that makes the subsystem easier to use.
- Reorganize a system with many subsystems into identifiable layers with single entry points
- Simplify the interface to a complex subsystem
Exemple
User.cs
|
public class User
{
public string Name { get; private set; }
public User(string name)
{
Name = name;
}
}
|
Group.cs
|
public class Group
{
public string Name { get; private set; }
public ICollection<User> Users { get; private set; }
public Group(string name)
{
Name = name;
Users = new List<User>();
}
}
|
UserService.cs
|
public class UserService
{
public User CreateUser(string userName) => new User(userName);
}
|
GroupService.cs
|
public class GroupService
{
IDictionary<string, Group> groupsByName;
public void AddUserIntoGroup(User user, Group group)
{
group.Users.Add(user);
}
public Group GetByName(string groupName)
=> groupsByName.TryGetValue(groupName, out var group) ? group : null;
}
|
UserGroupFacade.cs
|
public class UserGroupFacade
{
UserService userService;
GroupService groupService;
public UserGroupFacade(UserService userService, GroupService groupService)
{
this.userService = userService;
this.groupService = groupService;
}
public void CreateAdminUser(string userName)
{
var user = userService.CreateUser(userName);
var adminGroup = groupService.GetByName("Admin");
groupService.AddUserIntoGroup(user, adminGroup);
}
}
|
|
var userService = new UserService();
var groupService = new GroupService();
var userGroupFacade = new UserGroupFacade(userService, groupService);
// create an admin user in 1 call instead of havind to call UserService.CreateUser + GroupService.GetByName + GroupService.AddUserIntoGroup
userGroupFacade.CreateAdminUser("Nicolas");
|