Spring中的设计模式

设计模式分为创建型、行为型和结构型

设计模式的6大原则:

  1、开闭原则:对扩展开放,对修改关闭

  2、里氏替换:任何父类出现的地方,子类都可以替换。子类不要重写和重载父类的方法

  3、接口隔离:接口最小化,实现的接口不应包含不需要的方法

  4、依赖倒置:细节依赖抽象,抽象不应该依赖细节;依赖接口而不依赖具体的类

  5、迪米特原则:减少类之间的耦合,调用依赖类封装好的方法,不对其进行修改

  6、单一职责:一个类只负责一项职责

  7、合成复用:多用组合,少用继承

1、建造者(Builder)模式

  建造者模式:又叫生成器模式。建造者模式可以将一个产品的内部表象与产品的生成过程分割开来,从而可以使一个建造过程生成具有不同的内部表象的产品对象。

  如果我们用了建造者模式,那么用户就只需指定需要建造的类型就可以得到它们,而具体建造的过程和细节就不需知道了。

  角色:

  建造者:Builder--抽象建造者类,即为创建一个产品对象的各个部件指定的抽象接口。

  具体建造者:实现Builder接口,构造和装配各个组件。

  指挥者:是构建一个使用Builder接口的对象,用来根据用户的需求构建具体的对象。

在Spring中BeanDefinitionBuilder就是使用了建造者模式。允许我们以编程的方式定义bean的类,为AbstractBeanDefinition抽象类的相关实现设置值,比如作用域,

工厂方法,属性等。

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.support;

import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.util.ObjectUtils;

/**
 * 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} 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;
    }
/**
     * The {@code BeanDefinition} 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 a static factory method to use for this definition,
     * to be called on this bean's class.
     */
    public BeanDefinitionBuilder setFactoryMethod(String factoryMethod) {
        this.beanDefinition.setFactoryMethodName(factoryMethod);
        return this;
    }

    /**
     * Set the name of a non-static factory method to use for this definition,
     * including the bean name of the factory instance to call the method on.
     * @since 4.3.6
     */
    public BeanDefinitionBuilder setFactoryMethodOnBean(String factoryMethod, String factoryBean) {
        this.beanDefinition.setFactoryMethodName(factoryMethod);
        this.beanDefinition.setFactoryBeanName(factoryBean);
        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}.
     * This variant just remains around for Spring Security 2.x compatibility.
     */
    @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 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;
    }
...
}

2、工厂模式(静态工厂方法)

  这种模式允许通过使用静态方法对象进行初始化,称为工厂方法。在Spring中,可以通过指定的工厂方法创建bean。

  如DefaultListableBeanFactory的

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        return getBean(requiredType, (Object[]) null);
    }

    @Override
    public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
        NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args);
        if (namedBean != null) {
            return namedBean.getBeanInstance();
        }
        BeanFactory parent = getParentBeanFactory();
        if (parent != null) {
            return parent.getBean(requiredType, args);
        }
        throw new NoSuchBeanDefinitionException(requiredType);
    }

3、抽象工厂模式

  创建工厂的工厂,提供了一种创建对象的最佳方式。  如指定创建bean的工厂,将工厂bean注册到beanFactory中 

4、单例模式

  一个类只能有一个实例。

5、代理模式

  如AOP中的代理类就是

6、装饰器模式(Decorator)

  也叫包装器模式(Wrapper)

  动态的添加功能,属于合成/复用原则,通过组合,实现松耦合。装饰者和被装饰者实现同一个接口

  动态的给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

  Spring中用到的包装器模式在类名上有两种表现:一种是类名中含有Wapper,另一种是类名中含有Decorator。如BeanWrapper

7、适配器模式

  Spring内部大量使用了适配器模式,比如JpaVendorAdapter、HibernateJpaVendorAdapter、HandlerInterceptorAdapter、SpringContextResourceAdapter等

  适配器模式作为两个不兼容的接口之间的桥梁,如读卡器是作为内存卡和笔记本之间的适配器。

  在适配器模式中,我们通过增加一个新的适配器类来解决接口不兼容的问题,使得原本没有任何关系的类可以协同工作,将两个接口解耦,不修改原有的结构,

增加一个适配器类来使两个接口关联起来。根据适配器类与被适配器的关系不同,适配器模式可以分为对象适配器和类适配器两种,在对象适配器中,适配器与被

适配器之间是关联关系;在类适配器中,适配器与被适配器之间是继承或者实现关系

   由于Java不允许多继承,所以适配器以对象适配器为主

  如:适配器类实现目标接口,然后组合了被适配器类,在重写的目标方法中实际调用的是被适配器类的方法即可

   Spring AOP中用到了适配器模式。

8、观察者模式Observer:

  定义对象间的一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都得道通知并被自动刷新。

  Spring中的Listener的实现用的就是观察者模式,如ApplicationListener

原文地址:https://www.cnblogs.com/yangyongjie/p/11049874.html