You could add code to the Account class, passing in a user's classification when the account is created. To each restricted method, you would add code that would check the user classification and throw an exception if the user did not have the proper access rights. Security-related code would quickly clutter your Account class, obscuring its business logic. You would be violating the Single-Responsibility Principle![12]
Instead, you will externalize the security restrictions into a proxy class. The Account class itself will remain almost completely untouched! We are going for the open-closed principle[13] herebuilding new functionality by adding new code, not by modifying existing code.
The use of proxies often calls for factories. The UML diagram in Figure 12.4 shows the complete solution for the security proxy, including the use of the class AccountFactory to return an instance of a SecureProxy. The client can think that it is interacting with a real Account, but it is instead interacting with a proxy that is able to respond to the same messages. Figure 12.4. Security ProxyThe AccountFactory class uses the dynamic proxy class Proxy to create the SecureProxy object. SecureProxy does not directly implement Accountable; instead, the Proxy class sets SecureProxy up to capture all incoming messages and redirect each to the InvocationHandler interface method invoke. |