1.策略模式

The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it

          策略模式UML图

 

2.策略模式组成

—抽象策略角色: 策略类,通常由一个接口或者抽象类实现。
—具体策略角色:包装了相关的算法和行为。
—环境角色:持有一个策略类的引用,最终给客户端调用。
 
3.spring AOP策略模式使用
分析角色
 —抽象策略角色--AopProxy
 —具体策略角色--Cglib2AopProx和JdkDynamicAopProxy
 —环境角色--ProxyCreatorSupport
调用方式:ProxyFactoryBean.java
 1     /**
 2      * Return the singleton instance of this class's proxy object,
 3      * lazily creating it if it hasn't been created already.
 4      * @return the shared singleton proxy
 5      */
 6     private synchronized Object getSingletonInstance() {
 7         if (this.singletonInstance == null) {
 8             this.targetSource = freshTargetSource();
 9             if (this.autodetectInterfaces && getProxiedInterfaces().length == 0 && !isProxyTargetClass()) {
10                 // Rely on AOP infrastructure to tell us what interfaces to proxy.
11                 Class targetClass = getTargetClass();
12                 if (targetClass == null) {
13                     throw new FactoryBeanNotInitializedException("Cannot determine target class for proxy");
14                 }
15                 setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, this.proxyClassLoader));
16             }
17             // Initialize the shared singleton instance.
18             super.setFrozen(this.freezeProxy);
19             this.singletonInstance = getProxy(createAopProxy());
20         }
21         return this.singletonInstance;
22     }

真实代码实现在DefaultAopProxyFactory.java

 1     public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
 2         if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
 3             Class targetClass = config.getTargetClass();
 4             if (targetClass == null) {
 5                 throw new AopConfigException("TargetSource cannot determine target class: " +
 6                         "Either an interface or a target is required for proxy creation.");
 7             }
 8             if (targetClass.isInterface()) {
 9                 return new JdkDynamicAopProxy(config);
10             }
11             if (!cglibAvailable) {
12                 throw new AopConfigException(
13                         "Cannot proxy target class because CGLIB2 is not available. " +
14                         "Add CGLIB to the class path or specify proxy interfaces.");
15             }
16             return CglibProxyFactory.createCglibProxy(config);
17         }
18         else {
19             return new JdkDynamicAopProxy(config);
20         }
21     }

 

 
 
posted on 2013-03-21 17:22  一天不进步,就是退步  阅读(1627)  评论(0编辑  收藏  举报