Restrict the callers of a method to objects of a particular class
public class AuthorizedUser {
private static AuthorizedUser au = new AuthorizedUser();
private AuthorizedUser() {}
public validateAuthorization() {}
public static ProtectedResource doAuthorizedUserStuff() {
// Do authorized user stuff
...
// Do stuff with protected resource
ProtectedResource.doStuff(au);
// Do more authorized user stuff
...
}
}
public class ProtectedResource {
public static ProtectedResource doStuff(AuthorizedUser au) {
// Make sure the caller of this method has the token
au.validateAuthorization();
// Do protected resource stuff
...
}
}
If the caller doesn't provide an AuthorizedUser object, the call to AuthorizedUser.validateAuthorization() will throw an exception. But AuthorizedUser's constructor is private, so the only way the call can succeed is if AuthorizedUser makes the call and passes it's only instance, or if AuthorizedUser gives a reference to its instance to another object and that object uses the AuthorizedUser instance to make the call.
This makes it possible to set up trust relationships where an authorized class gives a reference to its instance to other classes it trusts.
Unlike the friend declaration in C++, this method does not break encapsulation.
Pattern invented: August 15, 2003