Recipe 23.4. Applying the Policy Design PatternProblemYou want to define a set of development rules within a policy that can be applied to your application's structure. SolutionApply the Policy aspect-oriented design pattern. Figure 23-4 shows the key components of the Policy pattern. Figure 23-4. The structure of the Policy patternThe key roles in the Policy pattern shown in Figure 23-4 are:
DiscussionThe Policy pattern can declare a set of rules for any area within your application. Those rules can vary from being compiler errors and warnings to overriding the use of certain classes and libraries. Example 23-5 is modified from Recipe 22.1 and shows how the Policy pattern can be implemented in AspectJ to specify a top-level policy for an example application that contains one rule stating that if the Java System.out.println(..) method is called then a warning is to be issued at compilation time. Example 23-5. An example of the policy pattern being applying top level rules to an applicationpublic abstract aspect ProjectPolicyAspect { protected abstract pointcut allowedSystemOuts( ); declare warning : call(* *.println(..)) && !allowedSystemOuts( ) && !BorderControllerAspect.withinTestingRegion( ) : "System.out usage detected. Suggest using logging?"; } Because, in this example, the top-level policy aspect is abstract and declares an abstract pointcut that can be used to override the System.out.println(..) rule, it can then be specialized for different areas within the target application, as shown in Example 23-6. Example 23-6. Extending an abstract top-level policypublic aspect MyAppPolicyAspect extends ProjectPolicyAspect { /** * Specifies regions within the application where messages * to System.out are allowed. */ protected pointcut allowedSystemOuts( ) : BorderControllerAspect.withinMyAppMainMethod( ) || BorderControllerAspect.withinThirdParty( ) || BorderControllerAspect.withinTestingRegion( ); } Here are the key characteristics of the Policy pattern:
The Policy pattern is useful in the following circumstances:
The Policy pattern can collaborate with the following design patterns:
You may want to define specialized policies for different areas of your application building on the Border Controller design pattern. See AlsoExtending the compiler to include new warnings and errors is shown in Recipe 16.6; how to implement the Proxy object-oriented pattern using aspect-oriented techniques is shown in Recipe 18.6; the Cuckoo's Egg aspect-oriented design pattern is explained in Recipe 23.1; the Border Controller aspect-oriented design pattern is explained in Recipe 23.3. |