Video in progress
What is the Facade pattern and when is it useful?
A Facade puts one simple entry point on top of a complex subsystem. The caller works with one method instead of ten classes, and the internal details stay hidden.
📖 Answer
For example, when a user signs up: write to the database, hash the password, send an email, grant a bonus, write an audit log. If the controller calls all of this itself, it gets tied to far too many things.
@Service
public class RegistrationFacade {
private final UserRepository users;
private final PasswordEncoder encoder;
private final MailService mail;
private final BonusService bonus;
// constructor shortened
@Transactional
public UserDto register(SignupRequest req) {
var user = users.save(new User(req.email(), encoder.encode(req.password())));
bonus.grantWelcome(user);
mail.sendWelcome(user);
return UserDto.from(user);
}
}
The controller now just says registrationFacade.register(req).
A Facade doesn't lock the internal classes away: if needed, they can be used directly. It just makes a common scenario easier. In practice, many "service" classes in Spring are really acting as facades.
Sign up to mark studied questions and save your progress.