Flink SQL JSON Format 源码解析

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
全局流量管理 GTM,标准版 1个月
简介: 用 Flink SQL 解析 JSON 格式的数据是非常简单的,只需要在 DDL 语句中设置 Format 为 json 即可,像下面这样:CREATE TABLE kafka_source ( funcName STRING, data ROW<snapshots ARRAY<ROW<content_type STRING,url STRING>>,audio ARRAY<ROW<content_type STRING,url STRING>>>, resultMap ROW<`result` MAP<STRING,STRING>,isSuccess BOOLEAN

用 Flink SQL 解析 JSON 格式的数据是非常简单的,只需要在 DDL 语句中设置 Format 为 json 即可,像下面这样:


CREATE TABLE kafka_source (
    funcName STRING,
    data ROW<snapshots ARRAY<ROW<content_type STRING,url STRING>>,audio ARRAY<ROW<content_type STRING,url STRING>>>,
    resultMap ROW<`result` MAP<STRING,STRING>,isSuccess BOOLEAN>,
    meta  MAP<STRING,STRING>,
    `type` INT,
    `timestamp` BIGINT,
    arr ARRAY<ROW<address STRING,city STRING>>,
    map MAP<STRING,INT>,
    doublemap MAP<STRING,MAP<STRING,INT>>,
    proctime as PROCTIME()
) WITH (
    'connector' = 'kafka', -- 使用 kafka connector
    'topic' = 'test',  -- kafka topic
    'properties.bootstrap.servers' = 'master:9092,storm1:9092,storm2:9092',  -- broker连接信息
    'properties.group.id' = 'jason_flink_test', -- 消费kafka的group_id
    'scan.startup.mode' = 'latest-offset',  -- 读取数据的位置
    'format' = 'json',  -- 数据源格式为 json
    'json.fail-on-missing-field' = 'true', -- 字段丢失任务不失败
    'json.ignore-parse-errors' = 'false'  -- 解析失败跳过
)


那么你有没有想过它的底层是怎么实现的呢? 今天这篇文章就带你深入浅出,了解其实现细节.


当你输入一条 SQL 的时候在 Flink 里面会经过解析,验证,优化,转换等几个重要的步骤,因为前面的几个过程比较繁琐,这里暂时不展开说明,我们直接来到比较关键的源码处,在把 sqlNode 转换成 relNode 的过程中,会来到 CatalogSourceTable#createDynamicTableSource 该类的作用是把 Calcite 的 RelOptTable 翻译成 Flink 的 TableSourceTable 对象.


createDynamicTableSource  源码


private DynamicTableSource createDynamicTableSource(
        FlinkContext context, ResolvedCatalogTable catalogTable) {
    final ReadableConfig config = context.getTableConfig().getConfiguration();
    return FactoryUtil.createTableSource(
            schemaTable.getCatalog(),
            schemaTable.getTableIdentifier(),
            catalogTable,
            config,
            Thread.currentThread().getContextClassLoader(),
            schemaTable.isTemporary());
}


其实这个就是要创建 Kafka Source 的流表,然后会调用 FactoryUtil#createTableSource 这个方法


createTableSource 源码


public static DynamicTableSource createTableSource(
        @Nullable Catalog catalog,
        ObjectIdentifier objectIdentifier,
        ResolvedCatalogTable catalogTable,
        ReadableConfig configuration,
        ClassLoader classLoader,
        boolean isTemporary) {
    final DefaultDynamicTableContext context =
            new DefaultDynamicTableContext(
                    objectIdentifier, catalogTable, configuration, classLoader, isTemporary);
    try {
        // 获取对应的 factory 这里其实就是 KafkaDynamicTableFactory
        final DynamicTableSourceFactory factory =
                getDynamicTableFactory(DynamicTableSourceFactory.class, catalog, context);
        // 创建动态表
        return factory.createDynamicTableSource(context);
    } catch (Throwable t) {
        throw new ValidationException(
                String.format(
                        "Unable to create a source for reading table '%s'.\n\n"
                                + "Table options are:\n\n"
                                + "%s",
                        objectIdentifier.asSummaryString(),
                        catalogTable.getOptions().entrySet().stream()
                                .map(e -> stringifyOption(e.getKey(), e.getValue()))
                                .sorted()
                                .collect(Collectors.joining("\n"))),
                t);
    }
}


在这个方法里面,有两个重要的过程,首先是获取对应的 factory 对象,然后创建 DynamicTableSource 实例.在 getDynamicTableFactory 中实际调用的是 discoverFactory 方法,顾名思义就是发现工厂.


discoverFactory 源码


public static <T extends Factory> T discoverFactory(
        ClassLoader classLoader, Class<T> factoryClass, String factoryIdentifier) {
    final List<Factory> factories = discoverFactories(classLoader);
    final List<Factory> foundFactories =
            factories.stream()
                    .filter(f -> factoryClass.isAssignableFrom(f.getClass()))
                    .collect(Collectors.toList());
    if (foundFactories.isEmpty()) {
        throw new ValidationException(
                String.format(
                        "Could not find any factories that implement '%s' in the classpath.",
                        factoryClass.getName()));
    }
    final List<Factory> matchingFactories =
            foundFactories.stream()
                    .filter(f -> f.factoryIdentifier().equals(factoryIdentifier))
                    .collect(Collectors.toList());
    if (matchingFactories.isEmpty()) {
        throw new ValidationException(
                String.format(
                        "Could not find any factory for identifier '%s' that implements '%s' in the classpath.\n\n"
                                + "Available factory identifiers are:\n\n"
                                + "%s",
                        factoryIdentifier,
                        factoryClass.getName(),
                        foundFactories.stream()
                                .map(Factory::factoryIdentifier)
                                .distinct()
                                .sorted()
                                .collect(Collectors.joining("\n"))));
    }
    if (matchingFactories.size() > 1) {
        throw new ValidationException(
                String.format(
                        "Multiple factories for identifier '%s' that implement '%s' found in the classpath.\n\n"
                                + "Ambiguous factory classes are:\n\n"
                                + "%s",
                        factoryIdentifier,
                        factoryClass.getName(),
                        matchingFactories.stream()
                                .map(f -> f.getClass().getName())
                                .sorted()
                                .collect(Collectors.joining("\n"))));
    }
    return (T) matchingFactories.get(0);
}


这个代码相对简单,就不加注释了,逻辑也非常的清晰,就是获取对应的 factory ,先是通过 SPI 机制加载所有的 factory 然后根据 factoryIdentifier 过滤出满足条件的,这里其实就是 kafka connector 了.最后还有一些异常的判断.


discoverFactories 源码


private static List<Factory> discoverFactories(ClassLoader classLoader) {
    try {
        final List<Factory> result = new LinkedList<>();
        ServiceLoader.load(Factory.class, classLoader).iterator().forEachRemaining(result::add);
        return result;
    } catch (ServiceConfigurationError e) {
        LOG.error("Could not load service provider for factories.", e);
        throw new TableException("Could not load service provider for factories.", e);
    }
}


这个代码大家应该比较熟悉了,前面也有文章介绍过了.加载所有的 Factory 返回一个 Factory 的集合.


下面才是今天的重点.


createDynamicTableSource 源码


public DynamicTableSource createDynamicTableSource(Context context) {
    TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context);
    ReadableConfig tableOptions = helper.getOptions();
    Optional<DecodingFormat<DeserializationSchema<RowData>>> keyDecodingFormat = getKeyDecodingFormat(helper);
    // format 的逻辑
    DecodingFormat<DeserializationSchema<RowData>> valueDecodingFormat = getValueDecodingFormat(helper);
    helper.validateExcept(new String[]{"properties."});
    KafkaOptions.validateTableSourceOptions(tableOptions);
    validatePKConstraints(context.getObjectIdentifier(), context.getCatalogTable(), valueDecodingFormat);
    StartupOptions startupOptions = KafkaOptions.getStartupOptions(tableOptions);
    Properties properties = KafkaOptions.getKafkaProperties(context.getCatalogTable().getOptions());
    properties.setProperty("flink.partition-discovery.interval-millis", String.valueOf(tableOptions.getOptional(KafkaOptions.SCAN_TOPIC_PARTITION_DISCOVERY).map(Duration::toMillis).orElse(-9223372036854775808L)));
    DataType physicalDataType = context.getCatalogTable().getSchema().toPhysicalRowDataType();
    int[] keyProjection = KafkaOptions.createKeyFormatProjection(tableOptions, physicalDataType);
    int[] valueProjection = KafkaOptions.createValueFormatProjection(tableOptions, physicalDataType);
    String keyPrefix = (String)tableOptions.getOptional(KafkaOptions.KEY_FIELDS_PREFIX).orElse((Object)null);
    return this.createKafkaTableSource(physicalDataType, (DecodingFormat)keyDecodingFormat.orElse((Object)null), valueDecodingFormat, keyProjection, valueProjection, keyPrefix, KafkaOptions.getSourceTopics(tableOptions), KafkaOptions.getSourceTopicPattern(tableOptions), properties, startupOptions.startupMode, startupOptions.specificOffsets, startupOptions.startupTimestampMillis);
}
getValueDecodingFormat 方法最终会调用 discoverOptionalFormatFactory 方法
discoverOptionalDecodingFormat 和 discoverOptionalFormatFactory 源码
public <I, F extends DecodingFormatFactory<I>>
                Optional<DecodingFormat<I>> discoverOptionalDecodingFormat(
                        Class<F> formatFactoryClass, ConfigOption<String> formatOption) {
            return discoverOptionalFormatFactory(formatFactoryClass, formatOption)
                    .map(
                            formatFactory -> {
                                String formatPrefix = formatPrefix(formatFactory, formatOption);
                                try {
                                    return formatFactory.createDecodingFormat(
                                            context, projectOptions(formatPrefix));
                                } catch (Throwable t) {
                                    throw new ValidationException(
                                            String.format(
                                                    "Error creating scan format '%s' in option space '%s'.",
                                                    formatFactory.factoryIdentifier(),
                                                    formatPrefix),
                                            t);
                                }
                            });
        }
private <F extends Factory> Optional<F> discoverOptionalFormatFactory(
        Class<F> formatFactoryClass, ConfigOption<String> formatOption) {
    final String identifier = allOptions.get(formatOption);
    if (identifier == null) {
        return Optional.empty();
    }
    final F factory =
            discoverFactory(context.getClassLoader(), formatFactoryClass, identifier);
    String formatPrefix = formatPrefix(factory, formatOption);
    // log all used options of other factories
    consumedOptionKeys.addAll(
            factory.requiredOptions().stream()
                    .map(ConfigOption::key)
                    .map(k -> formatPrefix + k)
                    .collect(Collectors.toSet()));
    consumedOptionKeys.addAll(
            factory.optionalOptions().stream()
                    .map(ConfigOption::key)
                    .map(k -> formatPrefix + k)
                    .collect(Collectors.toSet()));
    return Optional.of(factory);
}
// 直接过滤出满足条件的 format 
public static <T extends Factory> T discoverFactory(
            ClassLoader classLoader, Class<T> factoryClass, String factoryIdentifier) {
        final List<Factory> factories = discoverFactories(classLoader);
        final List<Factory> foundFactories =
                factories.stream()
                        .filter(f -> factoryClass.isAssignableFrom(f.getClass()))
                        .collect(Collectors.toList());
        if (foundFactories.isEmpty()) {
            throw new ValidationException(
                    String.format(
                            "Could not find any factories that implement '%s' in the classpath.",
                            factoryClass.getName()));
        }
        final List<Factory> matchingFactories =
                foundFactories.stream()
                        .filter(f -> f.factoryIdentifier().equals(factoryIdentifier))
                        .collect(Collectors.toList());
        if (matchingFactories.isEmpty()) {
            throw new ValidationException(
                    String.format(
                            "Could not find any factory for identifier '%s' that implements '%s' in the classpath.\n\n"
                                    + "Available factory identifiers are:\n\n"
                                    + "%s",
                            factoryIdentifier,
                            factoryClass.getName(),
                            foundFactories.stream()
                                    .map(Factory::factoryIdentifier)
                                    .distinct()
                                    .sorted()
                                    .collect(Collectors.joining("\n"))));
        }
        if (matchingFactories.size() > 1) {
            throw new ValidationException(
                    String.format(
                            "Multiple factories for identifier '%s' that implement '%s' found in the classpath.\n\n"
                                    + "Ambiguous factory classes are:\n\n"
                                    + "%s",
                            factoryIdentifier,
                            factoryClass.getName(),
                            matchingFactories.stream()
                                    .map(f -> f.getClass().getName())
                                    .sorted()
                                    .collect(Collectors.joining("\n"))));
        }
        return (T) matchingFactories.get(0);
    }


这里的逻辑和上面加载 connector 的逻辑是一样的,同样通过 SPI 先加载所有的 format 然后根据 factoryIdentifier 过滤出满足条件的 format 这里其实就是 json 了. 返回 formatFactory 后开始创建 format 这个时候就会走到 JsonFormatFactory#createDecodingFormat 这个方法里面.真正的创建一个 DecodingFormat 对象.


createDecodingFormat 源码


@Override
    public DecodingFormat<DeserializationSchema<RowData>> createDecodingFormat(
            DynamicTableFactory.Context context, ReadableConfig formatOptions) {
        // 验证相关的参数
        FactoryUtil.validateFactoryOptions(this, formatOptions);
        // 验证 json.fail-on-missing-field 和 json.ignore-parse-errors
        validateDecodingFormatOptions(formatOptions);
  // 获取 json.fail-on-missing-field 和 json.ignore-parse-errors
        final boolean failOnMissingField = formatOptions.get(FAIL_ON_MISSING_FIELD);
        final boolean ignoreParseErrors = formatOptions.get(IGNORE_PARSE_ERRORS);
        // 获取 timestamp-format.standard
        TimestampFormat timestampOption = JsonOptions.getTimestampFormat(formatOptions);
        return new DecodingFormat<DeserializationSchema<RowData>>() {
            @Override
            public DeserializationSchema<RowData> createRuntimeDecoder(
                    DynamicTableSource.Context context, DataType producedDataType) {
                final RowType rowType = (RowType) producedDataType.getLogicalType();
                final TypeInformation<RowData> rowDataTypeInfo =
                        context.createTypeInformation(producedDataType);
                return new JsonRowDataDeserializationSchema(
                        rowType,
                        rowDataTypeInfo,
                        failOnMissingField,
                        ignoreParseErrors,
                        timestampOption);
            }
            @Override
            public ChangelogMode getChangelogMode() {
                return ChangelogMode.insertOnly();
            }
        };
    }


这里的逻辑也非常简单,首先会对 format 相关的参数进行验证, 然后验证 json.fail-on-missing-field 和 json.ignore-parse-errors 这两个参数.之后就开始创建 JsonRowDataDeserializationSchema 对象


JsonRowDataDeserializationSchema 源码


public JsonRowDataDeserializationSchema(
        RowType rowType,
        TypeInformation<RowData> resultTypeInfo,
        boolean failOnMissingField,
        boolean ignoreParseErrors,
        TimestampFormat timestampFormat) {
    if (ignoreParseErrors && failOnMissingField) {
        throw new IllegalArgumentException(
                "JSON format doesn't support failOnMissingField and ignoreParseErrors are both enabled.");
    }
    this.resultTypeInfo = checkNotNull(resultTypeInfo);
    this.failOnMissingField = failOnMissingField;
    this.ignoreParseErrors = ignoreParseErrors;
    this.runtimeConverter =
            new JsonToRowDataConverters(failOnMissingField, ignoreParseErrors, timestampFormat)
                    .createConverter(checkNotNull(rowType));
    this.timestampFormat = timestampFormat;
    boolean hasDecimalType =
            LogicalTypeChecks.hasNested(rowType, t -> t instanceof DecimalType);
    if (hasDecimalType) {
        objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    }
    objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
}


在构造方法里面最重要的是创建 JsonToRowDataConverter 对象,这里面方法的调用比较多,这里只重要的方法进行说明


createRowConverter 源码


public JsonToRowDataConverter createRowConverter(RowType rowType) {
    final JsonToRowDataConverter[] fieldConverters =
            rowType.getFields().stream()
                    .map(RowType.RowField::getType)
                    .map(this::createConverter)
                    .toArray(JsonToRowDataConverter[]::new);
    final String[] fieldNames = rowType.getFieldNames().toArray(new String[0]);
    return jsonNode -> {
        ObjectNode node = (ObjectNode) jsonNode;
        int arity = fieldNames.length;
        GenericRowData row = new GenericRowData(arity);
        for (int i = 0; i < arity; i++) {
            String fieldName = fieldNames[i];
            JsonNode field = node.get(fieldName);
            Object convertedField = convertField(fieldConverters[i], fieldName, field);
            row.setField(i, convertedField);
        }
        return row;
    };
}


因为是 JSON 格式的数据,所以是一个 ROW 类型,所以要先创建 JsonToRowDataConverter 对象,然后在这里会对每一个字段创建一个 fieldConverter 根据你在 DDL 里面定义的字段类型走不同的转换方法,比如 String 类型的数据会调用 convertToString 方法


convertToString 源码


private StringData convertToString(JsonNode jsonNode) {
    if (jsonNode.isContainerNode()) {
        return StringData.fromString(jsonNode.toString());
    } else {
        return StringData.fromString(jsonNode.asText());
    }
}


这里需要注意的是 string 类型的数据需要返回 StringData 类型不然会报类型转换异常的错.感兴趣的朋友可以看下其他类型是如何处理的.


到这里 JsonRowDataDeserializationSchema 对象就构造完成了.那后面其实就是优化,转换到翻译成 streamGraph 再后面的过程就和 datastream api 开发的任务一样了.


然后真正开始消费数据的时候,会走到 JsonRowDataDeserializationSchema#deserialize 方法对数据进行反序列化.


deserialize 源码


@Override
public RowData deserialize(@Nullable byte[] message) throws IOException {
    if (message == null) {
        return null;
    }
    try {
        return convertToRowData(deserializeToJsonNode(message));
    } catch (Throwable t) {
        if (ignoreParseErrors) {
            return null;
        }
        throw new IOException(
                format("Failed to deserialize JSON '%s'.", new String(message)), t);
    }
}


先会把数据反序列成 JsonNode 对象.


deserializeToJsonNode 源码


public JsonNode deserializeToJsonNode(byte[] message) throws IOException {
    return objectMapper.readTree(message);
}


可以看到 Flink 的内部是用 jackson 解析数据的.接着把 jsonNode 格式的数据转换成 RowData 格式的数据


convertToRowData 源码


public RowData convertToRowData(JsonNode message) {
    return (RowData) runtimeConverter.convert(message);
}


然后这里的调用其实和上面构造 JsonRowDataDeserializationSchema 的时候是一样的


return jsonNode -> {
    ObjectNode node = (ObjectNode) jsonNode;
    int arity = fieldNames.length;
    GenericRowData row = new GenericRowData(arity);
    for (int i = 0; i < arity; i++) {
        String fieldName = fieldNames[i];
        JsonNode field = node.get(fieldName);
        Object convertedField = convertField(fieldConverters[i], fieldName, field);
        row.setField(i, convertedField);
    }
    return row;
};


最终返回的是 GenericRowData 类型的数据,其实就是 RowData 类型的,因为是 RowData 的实现类.然后就会把反序列后的数据发送到下游了.


总结


这篇文章主要分析了 Flink SQL JSON Format 的相关源码,从构建 JsonRowDataDeserializationSchema 到反序列化数据 deserialize.因为篇幅原因,只展示每个环节最重要的代码,其实很多细节都直接跳过了.感兴趣的朋友也可以自己去调试一下代码.有时间的话会更新更多的实现细节.

相关实践学习
基于Hologres轻松玩转一站式实时仓库
本场景介绍如何利用阿里云MaxCompute、实时计算Flink和交互式分析服务Hologres开发离线、实时数据融合分析的数据大屏应用。
Linux入门到精通
本套课程是从入门开始的Linux学习课程,适合初学者阅读。由浅入深案例丰富,通俗易懂。主要涉及基础的系统操作以及工作中常用的各种服务软件的应用、部署和优化。即使是零基础的学员,只要能够坚持把所有章节都学完,也一定会受益匪浅。
相关文章
|
20天前
|
JSON 前端开发 搜索推荐
关于商品详情 API 接口 JSON 格式返回数据解析的示例
本文介绍商品详情API接口返回的JSON数据解析。最外层为`product`对象,包含商品基本信息(如id、name、price)、分类信息(category)、图片(images)、属性(attributes)、用户评价(reviews)、库存(stock)和卖家信息(seller)。每个字段详细描述了商品的不同方面,帮助开发者准确提取和展示数据。具体结构和字段含义需结合实际业务需求和API文档理解。
|
13天前
|
JSON 小程序 UED
微信小程序 app.json 配置文件解析与应用
本文介绍了微信小程序中 `app.json` 配置文件的详细
74 12
|
13天前
|
JSON 缓存 API
解析电商商品详情API接口系列,json数据示例参考
电商商品详情API接口是电商平台的重要组成部分,提供了商品的详细信息,支持用户进行商品浏览和购买决策。通过合理的API设计和优化,可以提升系统性能和用户体验。希望本文的解析和示例能够为开发者提供参考,帮助构建高效、可靠的电商系统。
32 12
|
18天前
|
SQL Java 数据库连接
如何在 Java 代码中使用 JSqlParser 解析复杂的 SQL 语句?
大家好,我是 V 哥。JSqlParser 是一个用于解析 SQL 语句的 Java 库,可将 SQL 解析为 Java 对象树,支持多种 SQL 类型(如 `SELECT`、`INSERT` 等)。它适用于 SQL 分析、修改、生成和验证等场景。通过 Maven 或 Gradle 安装后,可以方便地在 Java 代码中使用。
138 11
|
2月前
|
JSON JavaScript 前端开发
一次采集JSON解析错误的修复
两段采集来的JSON格式数据存在格式问题,直接使用PHP的`json_decode`会报错。解决思路包括:1) 手动格式化并逐行排查错误;2) 使用PHP-V8JS扩展在JavaScript环境中解析。具体方案一是通过正则表达式和字符串替换修复格式,方案二是利用V8Js引擎执行JS代码并返回JSON字符串,最终实现正确解析。 简介: 两段采集的JSON数据因掺杂JavaScript代码导致PHP解析失败。解决方案包括手动格式化修复和使用PHP-V8JS扩展在JavaScript环境中解析,确保JSON数据能被正确处理。
|
3月前
|
SQL IDE 数据库连接
IntelliJ IDEA处理大文件SQL:性能优势解析
在数据库开发和管理工作中,执行大型SQL文件是一个常见的任务。传统的数据库管理工具如Navicat在处理大型SQL文件时可能会遇到性能瓶颈。而IntelliJ IDEA,作为一个强大的集成开发环境,提供了一些高级功能,使其在执行大文件SQL时表现出色。本文将探讨IntelliJ IDEA在处理大文件SQL时的性能优势,并与Navicat进行比较。
45 4
|
3月前
|
SQL Java 数据库连接
canal-starter 监听解析 storeValue 不一样,同样的sql 一个在mybatis执行 一个在数据库操作,导致解析不出正确对象
canal-starter 监听解析 storeValue 不一样,同样的sql 一个在mybatis执行 一个在数据库操作,导致解析不出正确对象
|
3月前
|
SQL 监控 安全
员工上网行为监控软件:SQL 在数据查询监控中的应用解析
在数字化办公环境中,员工上网行为监控软件对企业网络安全和管理至关重要。通过 SQL 查询和分析数据库中的数据,企业可以精准了解员工的上网行为,包括基础查询、复杂条件查询、数据统计与分析等,从而提高网络管理和安全防护的效率。
49 0
|
3月前
|
监控 Java 应用服务中间件
高级java面试---spring.factories文件的解析源码API机制
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置、起步依赖和内嵌服务器等特性,极大地简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是spring.factories文件的解析源码API机制。
121 2
|
2月前
|
设计模式 存储 安全
【23种设计模式·全精解析 | 创建型模式篇】5种创建型模式的结构概述、实现、优缺点、扩展、使用场景、源码解析
创建型模式的主要关注点是“怎样创建对象?”,它的主要特点是"将对象的创建与使用分离”。这样可以降低系统的耦合度,使用者不需要关注对象的创建细节。创建型模式分为5种:单例模式、工厂方法模式抽象工厂式、原型模式、建造者模式。
【23种设计模式·全精解析 | 创建型模式篇】5种创建型模式的结构概述、实现、优缺点、扩展、使用场景、源码解析