• 设计模式—— 工厂方法模式(Factory Pattern)+ Spring相关源码


    一、工厂模式 / 工厂方法模式

    类型: 创建型模式
    目的: 可以将对象的创建使用代码分离,提供统一的接口来创建不同类型的对象。

    二、例子

    2.1 菜鸟例子

    2.1.1 定义要被创建对象

    public interface Shape {
       void draw();
    }
    
    • 1
    • 2
    • 3
    public class Rectangle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Rectangle::draw() method.");
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    public class Circle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Circle::draw() method.");
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.1.2 工厂类

    public class ShapeFactory {
     
       //使用 getShape 方法获取形状类型的对象
       public Shape getShape(String shapeType){
          if(shapeType == null){
             return null;
          }        
          if(shapeType.equalsIgnoreCase("CIRCLE")){
             return new Circle();
          } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
             return new Rectangle();
          }
          return null;
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2.1.3 使用

    public class FactoryPatternDemo {
     
       public static void main(String[] args) {
          ShapeFactory shapeFactory = new ShapeFactory();
     
          //获取 Circle 的对象,并调用它的 draw 方法
          Shape shape1 = shapeFactory.getShape("CIRCLE");
          shape1.draw();
     
          //获取 Rectangle 的对象,并调用它的 draw 方法
          Shape shape2 = shapeFactory.getShape("RECTANGLE");
          shape2.draw();
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2.2 Spring源码——AbstractBeanFactory

    public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    
    	public Object getBean(String name) throws BeansException {
            return this.doGetBean(name, (Class)null, (Object[])null, false);
        }
    
        protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
            String beanName = this.transformedBeanName(name);
            Object sharedInstance = this.getSingleton(beanName);
            Object beanInstance;
            if (sharedInstance != null && args == null) {
                if (this.logger.isTraceEnabled()) {
                    if (this.isSingletonCurrentlyInCreation(beanName)) {
                        this.logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
                    } else {
                        this.logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                    }
                }
    
                beanInstance = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
            } else {
                if (this.isPrototypeCurrentlyInCreation(beanName)) {
                    throw new BeanCurrentlyInCreationException(beanName);
                }
    
                BeanFactory parentBeanFactory = this.getParentBeanFactory();
                if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
                    String nameToLookup = this.originalBeanName(name);
                    if (parentBeanFactory instanceof AbstractBeanFactory) {
                        return ((AbstractBeanFactory)parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
                    }
    
                    if (args != null) {
                        return parentBeanFactory.getBean(nameToLookup, args);
                    }
    
                    if (requiredType != null) {
                        return parentBeanFactory.getBean(nameToLookup, requiredType);
                    }
    
                    return parentBeanFactory.getBean(nameToLookup);
                }
    
                if (!typeCheckOnly) {
                    this.markBeanAsCreated(beanName);
                }
    
                StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate").tag("beanName", name);
    
                try {
                    if (requiredType != null) {
                        beanCreation.tag("beanType", requiredType::toString);
                    }
    
                    RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
                    this.checkMergedBeanDefinition(mbd, beanName, args);
                    String[] dependsOn = mbd.getDependsOn();
                    String[] prototypeInstance;
                    if (dependsOn != null) {
                        prototypeInstance = dependsOn;
                        int var13 = dependsOn.length;
    
                        for(int var14 = 0; var14 < var13; ++var14) {
                            String dep = prototypeInstance[var14];
                            if (this.isDependent(beanName, dep)) {
                                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                            }
    
                            this.registerDependentBean(dep, beanName);
    
                            try {
                                this.getBean(dep);
                            } catch (NoSuchBeanDefinitionException var31) {
                                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", var31);
                            }
                        }
                    }
    
                    if (mbd.isSingleton()) {
                        sharedInstance = this.getSingleton(beanName, () -> {
                            try {
                                return this.createBean(beanName, mbd, args);
                            } catch (BeansException var5) {
                                this.destroySingleton(beanName);
                                throw var5;
                            }
                        });
                        beanInstance = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                    } else if (mbd.isPrototype()) {
                        prototypeInstance = null;
    
                        Object prototypeInstance;
                        try {
                            this.beforePrototypeCreation(beanName);
                            prototypeInstance = this.createBean(beanName, mbd, args);
                        } finally {
                            this.afterPrototypeCreation(beanName);
                        }
    
                        beanInstance = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                    } else {
                        String scopeName = mbd.getScope();
                        if (!StringUtils.hasLength(scopeName)) {
                            throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
                        }
    
                        Scope scope = (Scope)this.scopes.get(scopeName);
                        if (scope == null) {
                            throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                        }
    
                        try {
                            Object scopedInstance = scope.get(beanName, () -> {
                                this.beforePrototypeCreation(beanName);
    
                                Object var4;
                                try {
                                    var4 = this.createBean(beanName, mbd, args);
                                } finally {
                                    this.afterPrototypeCreation(beanName);
                                }
    
                                return var4;
                            });
                            beanInstance = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                        } catch (IllegalStateException var30) {
                            throw new ScopeNotActiveException(beanName, scopeName, var30);
                        }
                    }
                } catch (BeansException var32) {
                    beanCreation.tag("exception", var32.getClass().toString());
                    beanCreation.tag("message", String.valueOf(var32.getMessage()));
                    this.cleanupAfterBeanCreationFailure(beanName);
                    throw var32;
                } finally {
                    beanCreation.end();
                }
            }
    
            return this.adaptBeanInstance(name, beanInstance, requiredType);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143

    2.3 slf4j源码——SubstituteLoggerFactory

    public class SubstituteLoggerFactory implements ILoggerFactory {
    
    	 public synchronized Logger getLogger(String name) {
            SubstituteLogger logger = (SubstituteLogger)this.loggers.get(name);
            if (logger == null) {
                logger = new SubstituteLogger(name, this.eventQueue, this.postInitialization);
                this.loggers.put(name, logger);
            }
    
            return logger;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    三、其他设计模式

    创建型模式
    结构型模式

    行为型模式

  • 相关阅读:
    微服务:Nacos注册中心
    SpringBoot中15个常用启动扩展点,你用过几个?
    Spring源码(十六)bean实例化过程CreateBeanInstance方法
    技术专家说 | 如何基于 Spark 和 Z-Order 实现企业级离线数仓降本提效?
    【Make YOLO Great Again】YOLOv1-v7全系列大解析(Head篇)(尝鲜版)
    VoLTE端到端业务详解 | VoLTE用户呼叫流程
    HBase-12-HBase容灾策略
    Linux网络编程- ether_header & iphdr & tcphdr
    mysql练习1
    极限多标签学习之SwiftXML
  • 原文地址:https://blog.csdn.net/malu_record/article/details/134322090