新闻资讯

新闻资讯 行业动态

Spring框架中的设计模式——建设者模式

编辑:008     时间:2020-02-27

建设者模式

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

  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.  @Test

  3.  public void test() {

  4.    Programmer programmer = new Programmer.ProgrammerBuilder()

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

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

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

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

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

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

  11.  }

  12. }

  13. class Programmer {

  14.  private String firstName;

  15.  private String lastName;

  16.  private String address;

  17.  private String zipCode;

  18.  private String city;

  19.  private String[] languages;

  20.  private String[] projects;

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

  22.    this.firstName = fName;

  23.    this.lastName = lName;

  24.    this.address = addr;

  25.    this.zipCode = zip;

  26.    this.city = city;

  27.    this.languages = langs;

  28.    this.projects = projects;

  29.  }

  30.  public static class ProgrammerBuilder {

  31.    private String firstName;

  32.    private String lastName;

  33.    private String address;

  34.    private String zipCode;

  35.    private String city;

  36.    private String[] languages;

  37.    private String[] projects;

  38.    public ProgrammerBuilder setFirstName(String firstName) {

  39.      this.firstName = firstName;

  40.      return this;

  41.    }

  42.    public ProgrammerBuilder setLastName(String lastName) {

  43.      this.lastName = lastName;

  44.      return this;

  45.    }

  46.    public ProgrammerBuilder setAddress(String address) {

  47.      this.address = address;

  48.      return this;

  49.    }

  50.    public ProgrammerBuilder setZipCode(String zipCode) {

  51.      this.zipCode = zipCode;

  52.      return this;

  53.    }

  54.    public ProgrammerBuilder setCity(String city) {

  55.      this.city = city;

  56.      return this;

  57.    }

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

  59.      this.languages = languages;

  60.      return this;

  61.    }

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

  63.      this.projects = projects;

  64.      return this;

  65.    }

  66.    public Programmer build() {

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

  68.    }

  69.  }

  70.  @Override

  71.  public String toString() {

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

  73.  }

  74. }

可以看出,构建器后面隐藏了对象构造的复杂性,内部静态类接受链接方法的调用。在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.  // ... some not important methods for this article

  7.  // Some of building methods

  8.  /**

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

  10.    */

  11.  public BeanDefinitionBuilder setParentName(String parentName) {

  12.    this.beanDefinition.setParentName(parentName);

  13.    return this;

  14.  }

  15.  /**

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

  17.    */

  18.  public BeanDefinitionBuilder setFactoryMethod(String factoryMethod) {

  19.    this.beanDefinition.setFactoryMethodName(factoryMethod);

  20.    return this;

  21.  }

  22.  /**

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

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

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

  26.    */

  27.  @Deprecated

  28.  public BeanDefinitionBuilder addConstructorArg(Object value) {

  29.    return addConstructorArgValue(value);

  30.  }

  31.  /**

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

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

  34.    */

  35.  public BeanDefinitionBuilder addConstructorArgValue(Object value) {

  36.    this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(

  37.                    this.constructorArgIndex++, value);

  38.    return this;

  39.  }

  40.  /**

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

  42.    * @see #addConstructorArgValue(Object)

  43.    */

  44.  public BeanDefinitionBuilder addConstructorArgReference(String beanName) {

  45.    this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(

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

  47.    return this;

  48.  }

  49.  /**

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

  51.    */

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

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

  54.    return this;

  55.  }

  56.  /**

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

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

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

  60.    */

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

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

  63.    return this;

  64.  }

  65.  /**

  66.    * Set the init method for this definition.

  67.    */

  68.  public BeanDefinitionBuilder setInitMethodName(String methodName) {

  69.    this.beanDefinition.setInitMethodName(methodName);

  70.    return this;

  71.  }

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

  73.  /**

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

  75.    * @see #getBeanDefinition()

  76.    */

  77.  public AbstractBeanDefinition getRawBeanDefinition() {

  78.    return this.beanDefinition;

  79.  }

  80.  /**

  81.    * Validate and return the created BeanDefinition object.

  82.    */

  83.  public AbstractBeanDefinition getBeanDefinition() {

  84.    this.beanDefinition.validate();

  85.    return this.beanDefinition;

  86.  }

  87. }

原文链接:https://mp.weixin.qq.com/s/3AWW1OX5KwMDX4CM4c39kg

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

回复列表

相关推荐