Spring框架中的设计模式(二)

http://mp.weixin.qq.com/s?srcid=08307WYv15BiKvR3yZhAKlzD&scene=23&mid=2247484167&sn=0df951dc68e9d7c45bd2b9379c5f4093&idx=1&__biz=MzAxODcyNjEzNQ%3D%3D&chksm=9bd0ae9faca727895ee41fc160e20826c4a3d24aa44936d62bbee442c9f6cae6b3678da2d3f6&mpshare=1#rd

spring技术学习,更多知识请访问https://www.itkc8.com

代理模式

面向对象编程(OOP)可能是编程中最流行的概念。然而,Spring引入了另一种编码规范,面向切面编程(AOP)。为了简化定义,AOP是面向系统特定点的一种编程,如:异常抛出,特定类别方法的执行等.AOP允许在执行这些特定点之前或之后执行补充动作。如何实现这种操作?它可以通过监听器(listeners)进行。但在这种情况下,我们应该在只要可能存在调用的地方都需要定义监听器来进行监听(比如在一个方法的开始的地方)。这就是为什么Spring不采用这个idea。相反,Spring实现了一种能够通过额外的方法调用完成任务的设计模式 - 代理设计模式

代理就像对象的镜像一样。也正因为如此,代理对象不仅可以覆盖真实对象,还可以扩展其功能。因此,对于只能在屏幕上打印一些文本的对象,我们可以添加另一个对象来过滤显示单词。可以通过代理来定义第二个对象的调用。代理是封装真实对象的对象。例如,如果您尝试调用Waiter bean,那么您将调用该Bean的代理,其行为方式完全相同。

代理设计模式的一个很好的例子是org.springframework.aop.framework.ProxyFactoryBean。该工厂根据Spring bean构建AOP代理。该类实现了定义getObject()方法的 FactoryBean接口。此方法用于将需求 Bean的实例返回给 bean factory。在这种情况下,它不是返回的实例,而是 AOP代理。在执行代理对象的方法之前,可以通过调用补充方法来进一步“修饰”代理对象(其实所谓的静态代理不过是在装饰模式上加了个要不要你来干动作行为而已,而不是装饰模式什么也不做就加了件衣服,其他还得由你来全权完成)。

ProxyFactory的一个例子是:

 
  1. public class TestProxyAop {

  2.  

  3.  @Test

  4.  public void test() {

  5.    ProxyFactory factory = new ProxyFactory(new House());

  6.    factory.addInterface(Construction.class);

  7.    factory.addAdvice(new BeforeConstructAdvice());

  8.    factory.setExposeProxy(true);

  9.  

  10.    Construction construction = (Construction) factory.getProxy();

  11.    construction.construct();

  12.    assertTrue("Construction is illegal. "

  13.      + "Supervisor didn't give a permission to build "

  14.      + "the house", construction.isPermitted());

  15.  }

  16.  

  17. }

  18.  

  19. interface Construction {

  20.  public void construct();

  21.  public void givePermission();

  22.  public boolean isPermitted();

  23. }

  24.  

  25. class House implements Construction{

  26.  

  27.  private boolean permitted = false;

  28.  

  29.  @Override

  30.  public boolean isPermitted() {

  31.    return this.permitted;

  32.  }

  33.  

  34.  @Override

  35.  public void construct() {

  36.    System.out.println("I'm constructing a house");

  37.  }

  38.  

  39.  @Override

  40.  public void givePermission() {

  41.    System.out.println("Permission is given to construct a simple house");

  42.    this.permitted = true;

  43.  }

  44. }

  45.  

  46. class BeforeConstructAdvice implements MethodBeforeAdvice {

  47.  

  48.  @Override

  49.  public void before(Method method, Object[] arguments, Object target) throws Throwable {

  50.    if (method.getName().equals("construct")) {

  51.      ((Construction) target).givePermission();

  52.    }

  53.  }

  54.  

  55. }

这个测试应该通过,因为我们不直接在House实例上操作,而是代理它。代理调用第一个 BeforeConstructAdvice before方法(指向在执行目标方法之前执行,在我们的例子中为 construct())通过它,给出了一个“权限”来构造对象的字段(house)。代理层提供了一个额外新功能,因为它可以简单地分配给另一个对象。要做到这一点,我们只能在before方法之前修改过滤器。

复合模式

另一种结构模式是复合模式。在关于Spring中设计模式的第一篇文章中,我们使用构建器来构造复杂对象。另一种实现方法是使用复合模式。这种模式是基于具有共同行为的多个对象的存在,用于构建更大的对象。较大的对象仍然具有与最小对象相同的特征。那么用它来定义相同的行为。

复合对象的非Spring示例可以是一个写入HTML的文本对象,由包含span或em标签的段落组成:

 
  1. public class CompositeTest {

  2.  

  3.  @Test

  4.  public void test() {

  5.    TextTagComposite composite = new PTag();

  6.    composite.addTag(new SpanTag());

  7.    composite.addTag(new EmTag());

  8.  

  9.    // sample client code

  10.    composite.startWrite();

  11.    for (TextTag leaf : composite.getTags()) {

  12.      leaf.startWrite();

  13.      leaf.endWrite();

  14.    }

  15.    composite.endWrite();

  16.    assertTrue("Composite should contain 2 tags but it contains "+composite.getTags().size(), composite.getTags().size() == 2);

  17.  }

  18.  

  19. }

  20.  

  21.  

  22. interface TextTag {

  23.  public void startWrite();

  24.  public void endWrite();

  25. }

  26.  

  27. interface TextTagComposite extends TextTag {

  28.  public List<TextTag> getTags();

  29.  public void addTag(TextTag tag);

  30. }

  31.  

  32. class PTag implements TextTagComposite {

  33.  private List<TextTag> tags = new ArrayList<TextTag>();

  34.  

  35.  @Override

  36.  public void startWrite() {

  37.    System.out.println("<p>");

  38.  }

  39.  

  40.  @Override

  41.  public void endWrite() {

  42.    System.out.println("</p>");

  43.  }

  44.  

  45.  @Override

  46.  public List<TextTag> getTags() {

  47.    return tags;

  48.  }

  49.  

  50.  @Override

  51.  public void addTag(TextTag tag) {

  52.    tags.add(tag);

  53.  }

  54. }

  55.  

  56. class SpanTag implements TextTag {

  57.  

  58.  @Override

  59.  public void startWrite() {

  60.    System.out.println("<span>");

  61.  }

  62.  

  63.  @Override

  64.  public void endWrite() {

  65.    System.out.println("</span>");

  66.  }

  67.  

  68. }

  69.  

  70. class EmTag implements TextTag {

  71.  

  72.  @Override

  73.  public void startWrite() {

  74.    System.out.println("<em>");

  75.  }

  76.  

  77.  @Override

  78.  public void endWrite() {

  79.    System.out.println("</em>");

  80.  }

  81.  

  82. }

在这种情况下,可以看到一个复合对象。我们可以区分复合与非复合对象,因为第一个可以容纳一个或多个非复合对象( PTag类中的 privateListtags字段)。非复合对象称为叶子。 TextTag接口被称为组件,因为它为两个对象类型提供了共同的行为规范(有点像 Linux文件管理系统的有共同点的文件放在一个文件夹下进行管理,其实就是节点管理)。

Spring世界中,我们检索复合对象的概念是org.springframework.beans.BeanMetadataElement接口,用于配置 bean对象。它是所有继承对象的基本界面。现在,在一方面,我们有一个叶子,由org.springframework.beans.factory.parsing.BeanComponentDefinition表示,另一边是复合org.springframework.beans.factory.parsing.CompositeComponentDefinition CompositeComponentDefinition类似于组件,因为它包含addNestedComponent(ComponentDefinition component)方法,它允许将叶添加到私有final列表中 nestedComponents。您可以看到,由于此列表, BeanComponentDefinition CompositeComponentDefinition的组件是org.springframework.beans.factory.parsing.ComponentDefinition

 

策略模式

本文描述的第三个概念是策略设计模式。策略定义了通过不同方式完成相同事情的几个对象。完成任务的方式取决于采用的策略。举个例子说明,我们可以去一个国家。我们可以乘公共汽车,飞机,船甚至汽车去那里。所有这些方法将把我们运送到目的地国家。但是,我们将通过检查我们的银行帐户来选择最适应的方式。如果我们有很多钱,我们将采取最快的方式(可能是私人飞行)。如果我们没有足够的话,我们会采取最慢的(公车,汽车)。该银行账户作为确定适应策略的因素。

Spring在org.springframework.web.servlet.mvc.multiaction.MethodNameResolver类(过时,但不影响拿来研究)中使用策略设计模式。它是 MultiActionController(同样过时)的参数化实现。在开始解释策略之前,我们需要了解MultiActionController的实用性。这个类允许同一个类处理几种类型的请求。作为Spring中的每个控制器,MultiActionController执行方法来响应提供的请求。策略用于检测应使用哪种方法。解析过程在MethodNameResolver实现中实现,例如在同一个包中的ParameterMethodNameResolver中。方法可以通过多个条件解决:属性映射,HTTP请求参数或URL路径。

 
  1. @Override

  2. public String getHandlerMethodName(HttpServletRequest request) throws NoSuchRequestHandlingMethodException {

  3.  String methodName = null;

  4.  

  5.  // Check parameter names where the very existence of each parameter

  6.  // means that a method of the same name should be invoked, if any.

  7.  if (this.methodParamNames != null) {

  8.    for (String candidate : this.methodParamNames) {

  9.      if (WebUtils.hasSubmitParameter(request, candidate)) {

  10.        methodName = candidate;

  11.        if (logger.isDebugEnabled()) {

  12.          logger.debug("Determined handler method '" + methodName +

  13.            "' based on existence of explicit request parameter of same name");

  14.        }

  15.        break;

  16.      }

  17.    }

  18.  }

  19.  

  20.  // Check parameter whose value identifies the method to invoke, if any.

  21.  if (methodName == null && this.paramName != null) {

  22.    methodName = request.getParameter(this.paramName);

  23.    if (methodName != null) {

  24.      if (logger.isDebugEnabled()) {

  25.        logger.debug("Determined handler method '" + methodName +

  26.          "' based on value of request parameter '" + this.paramName + "'");

  27.      }

  28.    }

  29.  }

  30.  

  31.  if (methodName != null && this.logicalMappings != null) {

  32.    // Resolve logical name into real method name, if appropriate.

  33.    String originalName = methodName;

  34.    methodName = this.logicalMappings.getProperty(methodName, methodName);

  35.    if (logger.isDebugEnabled()) {

  36.      logger.debug("Resolved method name '" + originalName + "' to handler method '" + methodName + "'");

  37.    }

  38.  }

  39.  

  40.  if (methodName != null && !StringUtils.hasText(methodName)) {

  41.    if (logger.isDebugEnabled()) {

  42.      logger.debug("Method name '" + methodName + "' is empty: treating it as no method name found");

  43.    }

  44.    methodName = null;

  45.  }

  46.  

  47.  if (methodName == null) {

  48.    if (this.defaultMethodName != null) {

  49.      // No specific method resolved: use default method.

  50.      methodName = this.defaultMethodName;

  51.      if (logger.isDebugEnabled()) {

  52.        logger.debug("Falling back to default handler method '" + this.defaultMethodName + "'");

  53.      }

  54.    }

  55.    else {

  56.      // If resolution failed completely, throw an exception.

  57.      throw new NoSuchRequestHandlingMethodException(request);

  58.    }

  59.  }

  60.  

  61.  return methodName;

  62. }

正如我们在前面的代码中可以看到的,方法的名称通过提供的参数映射,URL中的预定义属性或参数存在来解决(默认情况下,该参数的名称是action)。

模板模式

本文提出的最后一个设计模式是模板方法。此模式定义了类行为的骨架,并将子步骤的某些步骤的延迟执行(具体就是下面例子中一个方法放在另一个方法中,只有调用另一方方法的时候这个方法才会执行,而且还可能会在其他行为方法之后按顺序执行)。其中写了一种方法(下面例子中的construct()),注意定义为final,起着同步器的角色。它以给定的顺序执行由子类定义的方法。在现实世界中,我们可以将模板方法与房屋建设进行比较。独立于建造房屋的公司,我们需要从建立基础开始,只有在我们完成之后才能做其他的工作。这个执行逻辑将被保存在一个我们不能改变的方法中。例如基础建设或刷墙会被作为一个模板方法中的方法,具体到建筑房屋的公司。我们可以在给定的例子中看到它:

 
  1. public class TemplateMethod {

  2.  

  3.  public static void main(String[] args) {

  4.    HouseAbstract house = new SeaHouse();

  5.    house.construct();

  6.  }

  7.  

  8. }

  9.  

  10. abstract class HouseAbstract {

  11.  protected abstract void constructFoundations();

  12.  protected abstract void constructWall();

  13.  

  14.  // template method

  15.  public final void construct() {

  16.    constructFoundations();

  17.    constructWall();

  18.  }

  19. }

  20.  

  21. class EcologicalHouse extends HouseAbstract {

  22.  

  23.  @Override

  24.  protected void constructFoundations() {

  25.    System.out.println("Making foundations with wood");

  26.  }

  27.  

  28.  @Override

  29.  protected void constructWall() {

  30.    System.out.println("Making wall with wood");

  31.  }

  32.  

  33. }

  34.  

  35. class SeaHouse extends HouseAbstract {

  36.  

  37.  @Override

  38.  protected void constructFoundations() {

  39.    System.out.println("Constructing very strong foundations");

  40.  }

  41.  

  42.  @Override

  43.  protected void constructWall() {

  44.    System.out.println("Constructing very strong wall");

  45.  }

  46.  

  47. }

该代码应该输出:

 
  1. Constructing very strong foundations

  2. Constructing very strong wall

Spring在org.springframework.context.support.AbstractApplicationContext类中使用模板方法。他们不是一个模板方法(在我们的例子中是construct ),而是多个。例如,getsFreshBeanFactory返回内部 bean工厂的新版本,调用两个抽象方法: refreshBeanFactory(刷新工厂bean)和 getBeanFactory(以获取更新的工厂bean)。这个方法和其他一些方法一样,用在public void refresh()中,抛出构造应用程序上下文的BeansException,IllegalStateException方法(这里会在后面Spring中与应用程序上下文分析中再次提到)。

我们可以从同一个包中的GenericApplicationContext找到一些通过模板方法所实现的抽象方法的实现的例子(说的有点拗口,多读几遍就好):

 
  1. /**

  2.  * Do nothing: We hold a single internal BeanFactory and rely on callers

  3.  * to register beans through our public methods (or the BeanFactory's).

  4.  * @see #registerBeanDefinition

  5.  */

  6. @Override

  7. protected final void refreshBeanFactory() throws IllegalStateException {

  8.  if (this.refreshed) {

  9.    throw new IllegalStateException(

  10.      "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");

  11.  }

  12.  this.beanFactory.setSerializationId(getId());

  13.  this.refreshed = true;

  14. }

  15.  

  16. @Override

  17. protected void cancelRefresh(BeansException ex) {

  18.  this.beanFactory.setSerializationId(null);

  19.  super.cancelRefresh(ex);

  20. }

  21.  

  22. /**

  23.  * Not much to do: We hold a single internal BeanFactory that will never

  24.  * get released.

  25.  */

  26. @Override

  27. protected final void closeBeanFactory() {

  28.  this.beanFactory.setSerializationId(null);

  29. }

  30.  

  31. /**

  32.  * Return the single internal BeanFactory held by this context

  33.  * (as ConfigurableListableBeanFactory).

  34.  */

  35. @Override

  36. public final ConfigurableListableBeanFactory getBeanFactory() {

  37.  return this.beanFactory;

  38. }

  39.  

  40. /**

  41.  * Return the underlying bean factory of this context,

  42.  * available for registering bean definitions.

  43.  * <p><b>NOTE:</b> You need to call {@link #refresh()} to initialize the

  44.  * bean factory and its contained beans with application context semantics

  45.  * (autodetecting BeanFactoryPostProcessors, etc).

  46.  * @return the internal bean factory (as DefaultListableBeanFactory)

  47.  */

  48. public final DefaultListableBeanFactory getDefaultListableBeanFactory() {

  49.  return this.beanFactory;

  50. }

经过上面这些可以让我们发现Spring如何通过使用行为和结构设计模式来更好地组织上下文(模板方法),并通过相应策略来解决执行方法。它使用两种结构设计模式,通过代理模式来简化AOP部分并通过复合模式来构造复杂对象。

spring技术学习,更多知识请访问https://www.itkc8.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值