Effective java 2中例子:
当构造函数中的参数很多,且只有少数为必须设置值时,可以使用Builder模式。
public class NutritionFacts { private final int servingSize; private final int servings; private final int calories; private final int fat; private final int sodium; private final int carbohydrate; public static class Builder { // Required parameters private final int servingSize; private final int servings; // Optional parameters - initialized to default values private int calories = 0; private int fat = 0; private int carbohydrate = 0; private int sodium = 0; public Builder(int servingSize, int servings) { this.servingSize = servingSize; this.servings = servings; } public Builder calories(int val) { calories = val; return this; } public Builder fat(int val) { fat = val; return this; } public Builder carbohydrate(int val) { carbohydrate = val; return this; } public Builder sodium(int val) { sodium = val; return this; } public NutritionFacts build() { return new NutritionFacts(this); } } private NutritionFacts(Builder builder) { servingSize = builder.servingSize; servings = builder.servings; calories = builder.calories; fat = builder.fat; sodium = builder.sodium; carbohydrate = builder.carbohydrate; } }
调用方式:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) .calories(100).sodium(35).carbohydrate(27).build();
Spring中例子:
BeanDefinitionBuilder 构建 Builder 实例后,设置对应值,最后通过 getBeanDefinition 方法,获取需要的实例,获取方法中有实例必要参数是否设置的检查,保证获取的实例是合法的。
/** * Programmatic means of constructing * {@link org.springframework.beans.factory.config.BeanDefinition BeanDefinitions} * using the builder pattern. Intended primarily for use when implementing Spring 2.0 * {@link org.springframework.beans.factory.xml.NamespaceHandler NamespaceHandlers}. * * @author Rod Johnson * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 */ public class BeanDefinitionBuilder { /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link GenericBeanDefinition}. */ public static BeanDefinitionBuilder genericBeanDefinition() { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new GenericBeanDefinition(); return builder; } /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link GenericBeanDefinition}. * @param beanClass the <code>Class</code> of the bean that the definition is being created for */ public static BeanDefinitionBuilder genericBeanDefinition(Class beanClass) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new GenericBeanDefinition(); builder.beanDefinition.setBeanClass(beanClass); return builder; } /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link GenericBeanDefinition}. * @param beanClassName the class name for the bean that the definition is being created for */ public static BeanDefinitionBuilder genericBeanDefinition(String beanClassName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new GenericBeanDefinition(); builder.beanDefinition.setBeanClassName(beanClassName); return builder; } /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link RootBeanDefinition}. * @param beanClass the <code>Class</code> of the bean that the definition is being created for */ public static BeanDefinitionBuilder rootBeanDefinition(Class beanClass) { return rootBeanDefinition(beanClass, null); } /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link RootBeanDefinition}. * @param beanClass the <code>Class</code> of the bean that the definition is being created for * @param factoryMethodName the name of the method to use to construct the bean instance */ public static BeanDefinitionBuilder rootBeanDefinition(Class beanClass, String factoryMethodName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new RootBeanDefinition(); builder.beanDefinition.setBeanClass(beanClass); builder.beanDefinition.setFactoryMethodName(factoryMethodName); return builder; } /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link RootBeanDefinition}. * @param beanClassName the class name for the bean that the definition is being created for */ public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName) { return rootBeanDefinition(beanClassName, null); } /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link RootBeanDefinition}. * @param beanClassName the class name for the bean that the definition is being created for * @param factoryMethodName the name of the method to use to construct the bean instance */ public static BeanDefinitionBuilder rootBeanDefinition(String beanClassName, String factoryMethodName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new RootBeanDefinition(); builder.beanDefinition.setBeanClassName(beanClassName); builder.beanDefinition.setFactoryMethodName(factoryMethodName); return builder; } /** * Create a new <code>BeanDefinitionBuilder</code> used to construct a {@link ChildBeanDefinition}. * @param parentName the name of the parent bean */ public static BeanDefinitionBuilder childBeanDefinition(String parentName) { BeanDefinitionBuilder builder = new BeanDefinitionBuilder(); builder.beanDefinition = new ChildBeanDefinition(parentName); return builder; } /** * The <code>BeanDefinition</code> instance we are creating. */ private AbstractBeanDefinition beanDefinition; /** * Our current position with respect to constructor args. */ private int constructorArgIndex; /** * Enforce the use of factory methods. */ private BeanDefinitionBuilder() { } /** * Return the current BeanDefinition object in its raw (unvalidated) form. * @see #getBeanDefinition() */ public AbstractBeanDefinition getRawBeanDefinition() { return this.beanDefinition; } /** * Validate and return the created BeanDefinition object. */ public AbstractBeanDefinition getBeanDefinition() { this.beanDefinition.validate(); return this.beanDefinition; } /** * Set the name of the parent definition of this bean definition. */ public BeanDefinitionBuilder setParentName(String parentName) { this.beanDefinition.setParentName(parentName); return this; } /** * Set the name of the factory method to use for this definition. */ public BeanDefinitionBuilder setFactoryMethod(String factoryMethod) { this.beanDefinition.setFactoryMethodName(factoryMethod); return this; } /** * Set the name of the factory bean to use for this definition. * @deprecated since Spring 2.5, in favor of preparing this on the * {@link #getRawBeanDefinition() raw BeanDefinition object} */ @Deprecated public BeanDefinitionBuilder setFactoryBean(String factoryBean, String factoryMethod) { this.beanDefinition.setFactoryBeanName(factoryBean); this.beanDefinition.setFactoryMethodName(factoryMethod); return this; } /** * Add an indexed constructor arg value. The current index is tracked internally * and all additions are at the present point. * @deprecated since Spring 2.5, in favor of {@link #addConstructorArgValue} */ @Deprecated public BeanDefinitionBuilder addConstructorArg(Object value) { return addConstructorArgValue(value); } /** * Add an indexed constructor arg value. The current index is tracked internally * and all additions are at the present point. */ public BeanDefinitionBuilder addConstructorArgValue(Object value) { this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue( this.constructorArgIndex++, value); return this; } /** * Add a reference to a named bean as a constructor arg. * @see #addConstructorArgValue(Object) */ public BeanDefinitionBuilder addConstructorArgReference(String beanName) { this.beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue( this.constructorArgIndex++, new RuntimeBeanReference(beanName)); return this; } /** * Add the supplied property value under the given name. */ public BeanDefinitionBuilder addPropertyValue(String name, Object value) { this.beanDefinition.getPropertyValues().add(name, value); return this; } /** * Add a reference to the specified bean name under the property specified. * @param name the name of the property to add the reference to * @param beanName the name of the bean being referenced */ public BeanDefinitionBuilder addPropertyReference(String name, String beanName) { this.beanDefinition.getPropertyValues().add(name, new RuntimeBeanReference(beanName)); return this; } /** * Set the init method for this definition. */ public BeanDefinitionBuilder setInitMethodName(String methodName) { this.beanDefinition.setInitMethodName(methodName); return this; } /** * Set the destroy method for this definition. */ public BeanDefinitionBuilder setDestroyMethodName(String methodName) { this.beanDefinition.setDestroyMethodName(methodName); return this; } /** * Set the scope of this definition. * @see org.springframework.beans.factory.config.BeanDefinition#SCOPE_SINGLETON * @see org.springframework.beans.factory.config.BeanDefinition#SCOPE_PROTOTYPE */ public BeanDefinitionBuilder setScope(String scope) { this.beanDefinition.setScope(scope); return this; } /** * Set whether or not this definition describes a singleton bean, * as alternative to {@link #setScope}. * @deprecated since Spring 2.5, in favor of {@link #setScope} */ @Deprecated public BeanDefinitionBuilder setSingleton(boolean singleton) { this.beanDefinition.setSingleton(singleton); return this; } /** * Set whether or not this definition is abstract. */ public BeanDefinitionBuilder setAbstract(boolean flag) { this.beanDefinition.setAbstract(flag); return this; } /** * Set whether beans for this definition should be lazily initialized or not. */ public BeanDefinitionBuilder setLazyInit(boolean lazy) { this.beanDefinition.setLazyInit(lazy); return this; } /** * Set the autowire mode for this definition. */ public BeanDefinitionBuilder setAutowireMode(int autowireMode) { beanDefinition.setAutowireMode(autowireMode); return this; } /** * Set the depency check mode for this definition. */ public BeanDefinitionBuilder setDependencyCheck(int dependencyCheck) { beanDefinition.setDependencyCheck(dependencyCheck); return this; } /** * Append the specified bean name to the list of beans that this definition * depends on. */ public BeanDefinitionBuilder addDependsOn(String beanName) { if (this.beanDefinition.getDependsOn() == null) { this.beanDefinition.setDependsOn(new String[] {beanName}); } else { String[] added = (String[]) ObjectUtils.addObjectToArray(this.beanDefinition.getDependsOn(), beanName); this.beanDefinition.setDependsOn(added); } return this; } /** * Set the role of this definition. */ public BeanDefinitionBuilder setRole(int role) { this.beanDefinition.setRole(role); return this; } /** * Set the source of this definition. * @deprecated since Spring 2.5, in favor of preparing this on the * {@link #getRawBeanDefinition() raw BeanDefinition object} */ @Deprecated public BeanDefinitionBuilder setSource(Object source) { this.beanDefinition.setSource(source); return this; } /** * Set the description associated with this definition. * @deprecated since Spring 2.5, in favor of preparing this on the * {@link #getRawBeanDefinition() raw BeanDefinition object} */ @Deprecated public BeanDefinitionBuilder setResourceDescription(String resourceDescription) { this.beanDefinition.setResourceDescription(resourceDescription); return this; } }
调用 代码
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DeclareParentsAdvisor.class); builder.addConstructorArgValue(declareParentsElement.getAttribute(IMPLEMENT_INTERFACE)); builder.addConstructorArgValue(declareParentsElement.getAttribute(TYPE_PATTERN)); String defaultImpl = declareParentsElement.getAttribute(DEFAULT_IMPL); String delegateRef = declareParentsElement.getAttribute(DELEGATE_REF); if (StringUtils.hasText(defaultImpl) && !StringUtils.hasText(delegateRef)) { builder.addConstructorArgValue(defaultImpl); } else if (StringUtils.hasText(delegateRef) && !StringUtils.hasText(defaultImpl)) { builder.addConstructorArgReference(delegateRef); } else { parserContext.getReaderContext().error( "Exactly one of the " + DEFAULT_IMPL + " or " + DELEGATE_REF + " attributes must be specified", declareParentsElement, this.parseState.snapshot()); } AbstractBeanDefinition definition = builder.getBeanDefinition();
相关推荐
Builder设计模式是一种软件设计模式,它允许我们分步骤构建复杂对象,通过将构造过程与对象的表示分离,使得相同的构造过程可以创建不同的表示。在Java或者其他面向对象编程语言中,Builder模式经常被用来提高代码的...
Builder设计模式是一种结构型设计模式,它主要用于将复杂对象的构造过程与其表示分离,使得同样的构造过程可以创建不同的表示。这种模式通常在我们希望逐步构建一个对象,且构造过程复杂时使用,允许我们以一种独立...
Builder设计模式是创建型模式之一,主要解决复杂对象的构建问题,使得构建过程与表示分离。 Builder模式的核心思想是将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。这种模式通常应用于...
这份名为"设计模式例子文档,简单易学"的资源,显然是为了帮助开发者更直观、更快速地理解和应用设计模式。设计模式并非具体的代码或库,而是一种通用的解决方案模板,可以在不同的软件开发过程中复用,以提高代码的...
在深入探讨C#设计模式中的建造者(Builder)模式之前,我们先来理解一下什么是设计模式。设计模式是在软件工程中解决常见问题的一种通用可重用解决方案,它们提供了一种标准化的方法来解决软件开发中遇到的挑战。...
Builder模式是一种创建型设计模式,它提供了一种创建对象的灵活方式,将对象的构建过程与表示分离。这种模式在复杂对象的构造过程中特别有用,因为它允许我们通过不同的步骤来构造对象,而不会让客户端代码受到这些...
在这个“设计模式例子和PPT”压缩包中,包含的内容主要是关于设计模式的基本原则、UML类图以及一些实际的应用示例。 设计模式分为三大类:创建型模式、结构型模式和行为型模式。每种模式都有其特定的目标和适用场景...
设计模式是软件工程中的一种最佳实践,它是在特定上下文中解决常见问题的经验总结。这些模式在不同的编程语言中都有应用,而在这个压缩包中,我们重点关注的是与Java相关的设计模式。设计模式通常分为三大类:创建型...
java 设计模式 java 设计模式是软件工程的基石,它们被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式可以让代码更容易被他人理解、保证代码可靠性、提高代码的重用性。 一、设计模式...
Builder模式是一种创建型设计模式,它提供了一种方法来分步骤构建复杂的对象,使得构建过程和表示分离。这种模式在程序开发中常用于构造产品对象,尤其是当对象的构造过程较为复杂时,Builder模式能够帮助我们更好地...
在给定的压缩包文件中,"设计模式例子,观察者模式,建造者模式" 提到了两种重要的设计模式:观察者模式(Observer Pattern)和建造者模式(Builder Pattern)。下面我们将深入探讨这两种设计模式的概念、应用场景、...
- 生成器(Builder):快餐店制作儿童餐的过程就是生成器模式的一个例子,虽然套餐内容可能不同,但制作流程是标准化的。 - 原型(Prototype):生物学中的细胞分裂,每个细胞能复制自身,形成两个基因相同的细胞...
本压缩包文件“c#设计模式源码例子”提供了一组C#实现的设计模式示例,通过分析这些源码,我们可以深入理解并掌握各种设计模式的精髓。 首先,我们来看看几种主要的设计模式类别:创建型、结构型和行为型模式。 1....
### Java 23种设计模式详解 #### 一、设计模式概述 设计模式是一种编码实践,旨在通过标准化的解决方案来解决常见的软件设计问题。这些模式不仅有助于提高代码的可读性和可维护性,还能增强软件的灵活性和扩展性。...
Java设计模式中的Builder模式和Decorator模式是两种重要的设计模式,它们在软件开发中起到优化代码结构、提高代码复用性和灵活性的作用。 1. 建造者模式(Builder) 建造者模式是一种创建型设计模式,它的主要目的...
《研磨设计模式》在内容上深入、技术上实用、和实际开发结合程度很高,书中大部分的示例程序都是从实际项目中简化而来,因此很多例子都可以直接拿到实际项目中使用。如果你想要深入透彻地理解和掌握设计模式,并期望...
Builder模式是一种非常有用的设计模式,它可以使得对象的构建过程更加灵活和可控,但是也需要注意它的缺点,例如增加系统的复杂度和对象的构建时间。 在实际应用中,Builder模式可以应用于各种需要复杂对象构建的...
《Java设计模式之禅》是一本深入浅出讲解设计模式的书籍,书中不仅包含23种经典设计模式的案例,还详细介绍了设计模式背后的思想和原则,适合初学者以及对设计模式有一定了解的程序员阅读。本书旨在帮助读者理解如何...
Builder模式是一种设计模式,主要用来解决复杂对象的构建问题,特别是在对象的构造过程中涉及大量的参数时。在Java编程中,Builder模式提供了一种更加灵活、结构化的创建对象的方式,避免了构造函数的过度膨胀和...
设计模式是软件工程中的一种重要概念,它代表了在特定情境下解决常见问题的最佳实践。"设计模式可复用面向对象软件的基础"这一主题强调了设计模式在创建可维护、可扩展的面向对象软件中的核心作用。源码实现则为我们...