码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • 设计模式—— 工厂方法模式(Factory Pattern)+ Spring相关源码


    文章目录

    • 一、工厂模式 / 工厂方法模式
    • 二、例子
      • 2.1 菜鸟例子
        • 2.1.1 定义要被创建对象
        • 2.1.2 工厂类
        • 2.1.3 使用
      • 2.2 Spring源码——AbstractBeanFactory
      • 2.3 slf4j源码——SubstituteLoggerFactory
    • 三、其他设计模式

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

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

    二、例子

    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

    三、其他设计模式

    创建型模式
    结构型模式

    • 1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码

    行为型模式

    • 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
    • 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
    • 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
    • 4、设计模式——状态模式(State Pattern)
    • 5、设计模式——命令模式(Command Pattern)+ Spring相关源码
    • 6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码
    • 7、设计模式——备忘录模式(Memento Pattern)
    • 8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码
    • 9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码
    • 10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码
    • 11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码
  • 相关阅读:
    【python基础】python的继承与多态,子类中调用父类方法和属性
    CrossOver22试用期到了如何免费使用?
    Bootstrap的弹性盒子布局学习笔记
    Python(八十七)函数的定义与调用
    “基础不牢地动山摇“ ==> 重温 《内部类》
    更改当前动作路径为文件坐在地址路径,应对./这种情况,有利于项目移动
    Kubernetes部署Prometheus
    webpack快速入门-核心概念
    单目标应用:世界杯优化算法(World Cup Optimization,WCO)求解单仓库多旅行商问题SD-MTSP(可更改旅行商个数及起点)
    论文阅读 MAML (Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks)
  • 原文地址:https://blog.csdn.net/malu_record/article/details/134322090
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号