Say our application has beans that implement the following:
public interface Account { Account create(); String getId(); void changePassword(String password); }
We want to monitor how frequently the password on an account is changed to track potential hacking in our system. A decorator is an ideal way to solve the problem.
Our decorator is a bean, which can be abstract, that implements the required type and is annotated with @Decorator
:
@Decorator public abstract class PasswordMonitorDecorator implements Account { @Inject @Delegate @Any Account account; @PersistenceContext EntityManager em; public void changePassword(String password) { account.changePassword(password); em.persist(new PasswordChange(account.getId())); } }
As the decorator can be abstract, we only need to implement the methods of the type being decorated if our decorator needs to perform any special operations when that method is called.