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

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

设计模式有助于遵循良好的编程实践。作为最流行的Web框架之一的Spring框架也使用其中的一些。

本文将介绍Spring Framework中使用的设计模式。这是5篇专题文章的第一部分。这次我们将发现Spring框架中使用的4种设计模式:解释器,构建器,工厂方法和抽象工厂。每部分将首先解释给定模式的原理。紧接着,将会使用Spring的一个例子来加深理解。

解释器设计模式

在现实世界中,我们人类需要解释手势。他们可以对文化有不同的含义。这是我们的解释,给他们一个意义。在编程中,我们还需要分析一件事情,并决定它是什么意思。我们可以用解释设计模式来做。

此模式基于表达式和评估器部分。第一个代表一个要分析的事情。这个分析是由评价者来做出的,它们知道构成表达的人物的意义。不必要的操作是在一个上下文中进行的。

Spring主要以Spring Expression Language(SpEL)为例。这里快速提个醒,SpEL是一种由Spring的org.springframework.expression.ExpressionParser实现分析和执行的语言。这些实现使用作为字符串给出的Spel表达式,并将它们转换为org.springframework.expression.Expression的实例。上下文组件由org.springframework.expression.EvaluationContext实现表示,例如:StandardEvaluationContext。

举个SpEL的一个例子:

 
  1. Writer writer = new Writer();

  2. writer.setName("Writer's name");

  3. StandardEvaluationContext modifierContext = new StandardEvaluationContext(subscriberContext);

  4. modifierContext.setVariable("name", "Overriden writer's name");

  5. parser.parseExpression("name = #name").getValue(modifierContext);

  6. System.out.println("writer's name is : " + writer.getName());

输出应打印“Overriden writer’s name”。如你所见,一个对象的属性是通过一个表达式name = #name进行修改的,这个表达式只有在ExpressionParser才能理解,因为提供了context(前面的样例中的modifierContext实例)。

建设者模式

建设者设计模式是属于创建对象模式三剑客的第一种模式。该模式用于简化复杂对象的构造。要理解这个概念,想象一个说明程序员简历的对象。在这个对象中,我们想存储个人信息(名字,地址等)以及技术信息(知识语言,已实现的项目等)。该对象的构造可能如下所示:

 
  1. // with constructor

  2. Programmer programmer = new Programmer("first name", "last name", "address Street 39", "ZIP code", "City", "Country", birthDateObject, new String[] {"Java", "PHP", "Perl", "SQL"}, new String[] {"CRM system", "CMS system for government"});

  3. // or with setters

  4. Programmer programmer = new Programmer();

  5. programmer.setName("first name");

  6. programmer.setLastName("last name");

  7. // ... multiple lines after

  8. programmer.setProjects(new String[] {"CRM system", "CMS system for government"});

Builder允许我们通过使用将值传递给父类的内部构建器对象来清楚地分解对象构造。所以对于我们这个程序员简历的对象的创建,构建器可以看起来像:

 
  1. public class BuilderTest {

  2.  

  3.  @Test

  4.  public void test() {

  5.    Programmer programmer = new Programmer.ProgrammerBuilder()

  6.            .setFirstName("F").setLastName("L")

  7.            .setCity("City").setZipCode("0000A").setAddress("Street 39")

  8.            .setLanguages(new String[] {"bash", "Perl"})

  9.            .setProjects(new String[] {"Linux kernel"}).build();

  10.    assertTrue("Programmer should be 'F L' but was '" + programmer + "'",

  11.        programmer.toString().equals("F L"));

  12.  }

  13.  

  14. }

  15.  

  16. class Programmer {

  17.  private String firstName;

  18.  private String lastName;

  19.  private String address;

  20.  private String zipCode;

  21.  private String city;

  22.  private String[] languages;

  23.  private String[] projects;

  24.  

  25.  private Programmer(String fName, String lName, String addr, String zip, String city, String[] langs, String[] projects) {

  26.    this.firstName = fName;

  27.    this.lastName = lName;

  28.    this.address = addr;

  29.    this.zipCode = zip;

  30.    this.city = city;

  31.    this.languages = langs;

  32.    this.projects = projects;

  33.  }

  34.  

  35.  public static class ProgrammerBuilder {

  36.    private String firstName;

  37.    private String lastName;

  38.    private String address;

  39.    private String zipCode;

  40.    private String city;

  41.    private String[] languages;

  42.    private String[] projects;

  43.  

  44.    public ProgrammerBuilder setFirstName(String firstName) {

  45.      this.firstName = firstName;

  46.      return this;

  47.    }

  48.  

  49.    public ProgrammerBuilder setLastName(String lastName) {

  50.      this.lastName = lastName;

  51.      return this;

  52.    }

  53.  

  54.    public ProgrammerBuilder setAddress(String address) {

  55.      this.address = address;

  56.      return this;

  57.    }

  58.  

  59.    public ProgrammerBuilder setZipCode(String zipCode) {

  60.      this.zipCode = zipCode;

  61.      return this;

  62.    }

  63.  

  64.    public ProgrammerBuilder setCity(String city) {

  65.      this.city = city;

  66.      return this;

  67.    }

  68.  

  69.    public ProgrammerBuilder setLanguages(String[] languages) {

  70.      this.languages = languages;

  71.      return this;

  72.    }

  73.    public ProgrammerBuilder setProjects(String[] projects) {

  74.      this.projects = projects;

  75.      return this;

  76.    }

  77.  

  78.    public Programmer build() {

  79.      return new Programmer(firstName, lastName, address, zipCode, city, languages, projects);

  80.    }

  81.  }

  82.  

  83.  @Override

  84.  public String toString() {

  85.    return this.firstName + " "+this.lastName;

  86.  }

  87.  

  88. }

可以看出,构建器后面隐藏了对象构造的复杂性,内部静态类接受链接方法的调用。在Spring中,我们可以在org.springframework.beans.factory.support.BeanDefinitionBuilder类中检索这个逻辑。这是一个允许我们以编程方式定义bean的类。我们可以在关于bean工厂后处理器的文章中看到它,BeanDefinitionBuilder包含几个方法,它们为AbstractBeanDefinition抽象类的相关实现设置值,比如作用域,工厂方法,属性等。想看看它是如何工作的,请查看以下这些方法:

 
  1. public class BeanDefinitionBuilder {

  2.       /**

  3.    * The {@code BeanDefinition} instance we are creating.

  4.    */

  5.  private AbstractBeanDefinition beanDefinition;

  6.  

  7.  // ... some not important methods for this article

  8.  

  9.  // Some of building methods

  10.  /**

  11.    * Set the name of the parent definition of this bean definition.

  12.    */

  13.  public BeanDefinitionBuilder setParentName(String parentName) {

  14.    this.beanDefinition.setParentName(parentName);

  15.    return this;

  16.  }

  17.  

  18.  /**

  19.    * Set the name of the factory method to use for this definition.

  20.    */

  21.  public BeanDefinitionBuilder setFactoryMethod(String factoryMethod) {

  22.    this.beanDefinition.setFactoryMethodName(factoryMethod);

  23.    return this;

  24.  }

  25.  

  26.  /**

  27.    * Add an indexed constructor arg value. The current index is tracked internally

  28.    * and all additions are at the present point.

  29.    * @deprecated since Spring 2.5, in favor of {@link #addConstructorArgValue}

  30.    */

  31.  @Deprecated

  32.  public BeanDefinitionBuilder addConstructorArg(Object value) {

  33.    return addConstructorArgValue(value);

  34.  }

  35.  

  36.  /**

  37.    * Add an indexed constructor arg value. The current index is tracked internally

  38.    * and all additions are at the present point.

  39.    */

  40.  public BeanDefinitionBuilder addConstructorArgValue(Object value) {

  41.    this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(

  42.                    this.constructorArgIndex++, value);

  43.    return this;

  44.  }

  45.  

  46.  /**

  47.    * Add a reference to a named bean as a constructor arg.

  48.    * @see #addConstructorArgValue(Object)

  49.    */

  50.  public BeanDefinitionBuilder addConstructorArgReference(String beanName) {

  51.    this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(

  52.                    this.constructorArgIndex++, new RuntimeBeanReference(beanName));

  53.    return this;

  54.  }

  55.  

  56.  /**

  57.    * Add the supplied property value under the given name.

  58.    */

  59.  public BeanDefinitionBuilder addPropertyValue(String name, Object value) {

  60.    this.beanDefinition.getPropertyValues().add(name, value);

  61.    return this;

  62.  }

  63.  

  64.  /**

  65.    * Add a reference to the specified bean name under the property specified.

  66.    * @param name the name of the property to add the reference to

  67.    * @param beanName the name of the bean being referenced

  68.    */

  69.  public BeanDefinitionBuilder addPropertyReference(String name, String beanName) {

  70.    this.beanDefinition.getPropertyValues().add(name, new RuntimeBeanReference(beanName));

  71.    return this;

  72.  }

  73.  

  74.  /**

  75.    * Set the init method for this definition.

  76.    */

  77.  public BeanDefinitionBuilder setInitMethodName(String methodName) {

  78.    this.beanDefinition.setInitMethodName(methodName);

  79.    return this;

  80.  }

  81.  

  82.  // Methods that can be used to construct BeanDefinition

  83.  /**

  84.    * Return the current BeanDefinition object in its raw (unvalidated) form.

  85.    * @see #getBeanDefinition()

  86.    */

  87.  public AbstractBeanDefinition getRawBeanDefinition() {

  88.    return this.beanDefinition;

  89.  }

  90.  

  91.  /**

  92.    * Validate and return the created BeanDefinition object.

  93.    */

  94.  public AbstractBeanDefinition getBeanDefinition() {

  95.    this.beanDefinition.validate();

  96.    return this.beanDefinition;

  97.  }

  98. }

工厂方法

创建对象模式三剑客的第二个成员是工厂方法设计模式。它完全适于使用动态环境作为Spring框架。实际上,这种模式允许通过公共静态方法对象进行初始化,称为工厂方法。在这个概念中,我们需要定义一个接口来创建对象。但是创建是由使用相关对象的类创建的。

但是在跳到Spring世界之前,让我们用Java代码做一个例子:

 
  1. public class FactoryMethodTest {

  2.  

  3.  @Test

  4.  public void test() {

  5.    Meal fruit = Meal.valueOf("banana");

  6.    Meal vegetable = Meal.valueOf("carrot");

  7.    assertTrue("Banana should be a fruit but is "+fruit.getType(), fruit.getType().equals("fruit"));

  8.    assertTrue("Carrot should be a vegetable but is "+vegetable.getType(), vegetable.getType().equals("vegetable"));

  9.  }

  10.  

  11. }

  12.  

  13. class Meal {

  14.  

  15.  private String type;

  16.  

  17.  public Meal(String type) {

  18.    this.type = type;

  19.  }

  20.  

  21.  public String getType() {

  22.    return this.type;

  23.  }

  24.  

  25.  // Example of factory method - different object is created depending on current context

  26.  public static Meal valueOf(String ingredient) {

  27.    if (ingredient.equals("banana")) {

  28.      return new Meal("fruit");

  29.    }

  30.    return new Meal("vegetable");

  31.  }

  32. }

在Spring中,我们可以通过指定的工厂方法创建bean。该方法与以前代码示例中看到的valueOf方法完全相同。它是静态的,可以采取没有或多个参数。为了更好地了解案例,让我们来看一下实例。首先搞定下配置:

 
  1. <bean id="welcomerBean" class="com.mysite.Welcomer" factory-method="createWelcomer">

  2.    <constructor-arg ref="messagesLocator"></constructor-arg>

  3. </bean>

  4.  

  5. <bean id="messagesLocator" class="com.mysite.MessageLocator">

  6.    <property name="messages" value="messages_file.properties"></property>

  7. </bean>

现在请关注这个bean的初始化:

 
  1. public class Welcomer {

  2.  private String message;

  3.  

  4.  public Welcomer(String message) {

  5.    this.message = message;

  6.  }

  7.  

  8.  public static Welcomer createWelcomer(MessageLocator messagesLocator) {

  9.    Calendar cal = Calendar.getInstance();

  10.    String msgKey = "welcome.pm";

  11.    if (cal.get(Calendar.AM_PM) == Calendar.AM) {

  12.      msgKey = "welcome.am";

  13.    }

  14.    return new Welcomer(messagesLocator.getMessageByKey(msgKey));

  15.  }

  16. }

当Spring将构造welcomerBean时,它不会通过传统的构造函数,而是通过定义的静态工厂方法createWelcomer来实现。还要注意,这个方法接受一些参数(MessageLocator bean的实例包含所有可用的消息) 标签,通常保留给传统的构造函数。

抽象工厂

最后一个,抽象的工厂设计模式,看起来类似于工厂方法。不同之处在于,我们可以将抽象工厂视为这个词的工业意义上的工厂,即。作为提供所需对象的东西。工厂部件有:抽象工厂,抽象产品,产品和客户。更准确地说,抽象工厂定义了构建对象的方法。抽象产品是这种结构的结果。产品是具有同样结构的具体结果。客户是要求创造产品来抽象工厂的人。

同样的,在进入Spring的细节之前,我们将首先通过示例Java代码说明这个概念:

 
  1. public class FactoryTest {

  2.  

  3.  // Test method which is the client

  4.  @Test

  5.  public void test() {

  6.    Kitchen factory = new KitchenFactory();

  7.    KitchenMeal meal = factory.getMeal("P.1");

  8.    KitchenMeal dessert = factory.getDessert("I.1");

  9.    assertTrue("Meal's name should be 'protein meal' and was '"+meal.getName()+"'", meal.getName().equals("protein meal"));

  10.    assertTrue("Dessert's name should be 'ice-cream' and was '"+dessert.getName()+"'", dessert.getName().equals("ice-cream"));

  11.  }

  12.  

  13. }

  14.  

  15. // abstract factory

  16. abstract class Kitchen {

  17.  public abstract KitchenMeal getMeal(String preferency);

  18.  public abstract KitchenMeal getDessert(String preferency);

  19. }

  20.  

  21. // concrete factory

  22. class KitchenFactory extends Kitchen {

  23.  @Override

  24.  public KitchenMeal getMeal(String preferency) {

  25.    if (preferency.equals("F.1")) {

  26.      return new FastFoodMeal();

  27.    } else if (preferency.equals("P.1")) {

  28.      return new ProteinMeal();

  29.    }

  30.    return new VegetarianMeal();

  31.  }

  32.  

  33.  @Override

  34.  public KitchenMeal getDessert(String preferency) {

  35.    if (preferency.equals("I.1")) {

  36.      return new IceCreamMeal();

  37.    }

  38.    return null;

  39.  }

  40. }

  41.  

  42. // abstract product

  43. abstract class KitchenMeal {

  44.  public abstract String getName();

  45. }

  46.  

  47. // concrete products

  48. class ProteinMeal extends KitchenMeal {

  49.  @Override

  50.  public String getName() {

  51.    return "protein meal";

  52.  }

  53. }

  54.  

  55. class VegetarianMeal extends KitchenMeal {

  56.  @Override

  57.  public String getName() {

  58.    return "vegetarian meal";

  59.  }

  60. }

  61.  

  62. class FastFoodMeal extends KitchenMeal {

  63.  @Override

  64.  public String getName() {

  65.    return "fast-food meal";

  66.  }

  67. }

  68.  

  69. class IceCreamMeal extends KitchenMeal {

  70.  @Override

  71.  public String getName() {

  72.    return "ice-cream";

  73.  }

  74. }

我们可以在这个例子中看到,抽象工厂封装了对象的创建。对象创建可以使用与经典构造函数一样使用的工厂方法模式。在Spring中,工厂的例子是org.springframework.beans.factory.BeanFactory。通过它的实现,我们可以从Spring的容器访问bean。根据采用的策略,getBean方法可以返回已创建的对象(共享实例,单例作用域)或初始化新的对象(原型作用域)。在BeanFactory的实现中,我们可以区分:ClassPathXmlApplicationContext,XmlWebApplicationContext,StaticWebApplicationContext,StaticPortletApplicationContext,GenericApplicationContext,StaticApplicationContext。

 
  1. @RunWith(SpringJUnit4ClassRunner.class)

  2. @ContextConfiguration(locations={"file:test-context.xml"})

  3. public class TestProduct {

  4.  

  5.  @Autowired

  6.  private BeanFactory factory;

  7.  

  8.  @Test

  9.  public void test() {

  10.    System.out.println("Concrete factory is: "+factory.getClass());

  11.    assertTrue("Factory can't be null", factory != null);

  12.    ShoppingCart cart = (ShoppingCart) factory.getBean("shoppingCart");

  13.    assertTrue("Shopping cart object can't be null", cart != null);

  14.    System.out.println("Found shopping cart bean:"+cart.getClass());

  15.  }

  16. }

在这种情况下,抽象工厂由BeanFactory接口表示。具体工厂是在第一个System.out中打印的,是org.springframework.beans.factory.support.DefaultListableBeanFactory的实例。它的抽象产物是一个对象。在我们的例子中,具体的产品就是被强转为ShoppingCart实例的抽象产品(Object)。

第一篇文章介绍了通过设计模式来正确组织的我们实现良好的编程风格。在这里,我们可以看到在Spring框架中使用解释器,构建器,工厂方法和工厂。第一个是帮助解释以SpEL表达的文本。三个最后的模式属于创建设计模式的三剑客,它们在Spring中的主要目的是简化对象的创建。他们通过分解复杂对象(构建器)的初始化或通过集中在公共点的初始化来做到对象的创建(要不然怎么叫工厂呢,必须有通用点的)。

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值