CSharp: Prototype Pattern

项目结构:

这篇文章展示了一个基于C#原型设计模式(Prototype Pattern)实现的珠宝业务管理系统。系统通过定义BaseJewelryDocument基类和12种具体业务单据类型(如原料采购、设计制图、生产加工等),采用JSON序列化实现深拷贝。核心组件包括:

  1. 线程安全的ConcurrentPrototypePool原型池,管理预注册的业务单据模板
  2. JewelryTemplateInitializer初始化器统一加载业务模板
  3. JewelryBusinessFlowScheduler调度器编排完整业务流程
  4. 集成了统一日志系统,支持控制台和文件输出

该系统通过原型模式实现了业务单据的高效克隆,支持多线程并发操作,完整模拟了珠宝从原料采购到销售的全流程管理。

cs 复制代码
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : DesignDraftDoc.cs
 */
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 设计制图单据原型
    /// </summary>
    public class DesignDraftDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 首饰款式名称
        /// </summary>
        public string StyleName { get; set; } = string.Empty;
 
        /// <summary>
        /// 设计图纸地址
        /// </summary>
        public string DraftUrl { get; set; } = string.Empty;
 
        /// <summary>
        /// 设计师姓名
        /// </summary>
        public string Designer { get; set; } = string.Empty;
 
        /// <summary>
        /// 图纸版本号
        /// </summary>
        public int Version { get; set; }
 
        /// <summary>
        /// 客户是否确认定稿
        /// </summary>
        public bool CustomerConfirm { get; set; }
    }
}
 
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : FinanceBillDoc.cs
 */
 
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 财务单据原型
    /// </summary>
    public class FinanceBillDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 关联业务单据号
        /// </summary>
        public string RelateBizNo { get; set; } = string.Empty;
 
        /// <summary>
        /// 单据类型:采购支出/销售回款/加工费用
        /// </summary>
        public string BillType { get; set; } = string.Empty;
 
        /// <summary>
        /// 单据金额
        /// </summary>
        public decimal Amount { get; set; }
 
        /// <summary>
        /// 出纳
        /// </summary>
        public string Cashier { get; set; } = string.Empty;
 
        /// <summary>
        /// 支付方式
        /// </summary>
        public string PayWay { get; set; } = string.Empty;
 
        /// <summary>
        /// 是否审核通过
        /// </summary>
        public bool Audited { get; set; }
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : HrAdminDoc.cs
 */
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 人事行政单据原型
    /// </summary>
    public class HrAdminDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 员工工号
        /// </summary>
        public string StaffId { get; set; } = string.Empty;
 
        /// <summary>
        /// 员工姓名
        /// </summary>
        public string StaffName { get; set; } = string.Empty;
 
 
        /// <summary>
        /// 所属部门
        /// </summary>
        public string Department { get; set; } = string.Empty;
 
        /// <summary>
        /// 操作类型:入职/调岗/考勤/离职
        /// </summary>
        public string OperateType { get; set; } = string.Empty;
 
        /// <summary>
        /// 薪资
        /// </summary>
        public decimal Salary { get; set; }
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : ItOpsDoc.cs
 */
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// IT运维单据原型
    /// </summary>
    public class ItOpsDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 故障系统/设备
        /// </summary>
        public string DeviceSystem { get; set; } = string.Empty;
 
        /// <summary>
        /// 故障描述
        /// </summary>
        public string FaultDesc { get; set; } = string.Empty;
 
        /// <summary>
        /// 运维工程师
        /// </summary>
        public string Maintainer { get; set; } = string.Empty;
 
 
        /// <summary>
        /// 是否修复完成
        /// </summary>
        public bool Fixed { get; set; }
 
        /// <summary>
        /// 修复完成时间
        /// </summary>
        public DateTime FixFinishTime { get; set; }
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : LogisticsDoc.cs
 */
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
 
    /// <summary>
    /// 物流发货单据原型
    /// </summary>
    public class LogisticsDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 关联包装单号
        /// </summary>
        public string RelatePackNo { get; set; } = string.Empty;
 
        /// <summary>
        /// 物流公司
        /// </summary>
        public string Express { get; set; } = string.Empty;
 
        /// <summary>
        /// 物流运单号
        /// </summary>
        public string TrackNo { get; set; } = string.Empty;
 
        /// <summary>
        /// 收货地址
        /// </summary>
        public string ReceiveAddr { get; set; } = string.Empty;
 
        /// <summary>
        /// 收货人
        /// </summary>
        public string Receiver { get; set; } = string.Empty;
 
        /// <summary>
        /// 发货时间
        /// </summary>
        public DateTime ShipTime { get; set; }
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : MarketingPromoDoc.cs
 */
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 营销推广活动单据原型
    /// </summary>
    public class MarketingPromoDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 活动名称
        /// </summary>
        public string PromoName { get; set; } = string.Empty;
 
        /// <summary>
        /// 推广渠道:门店/短视频/直播
        /// </summary>
        public string Channel { get; set; } = string.Empty;
 
        /// <summary>
        /// 折扣比例
        /// </summary>
        public decimal DiscountRate { get; set; }
 
        /// <summary>
        /// 活动开始时间
        /// </summary>
        public DateTime StartTime { get; set; }
 
        /// <summary>
        /// 活动结束时间
        /// </summary>
        public DateTime EndTime { get; set; }
 
        /// <summary>
        /// 营销负责人
        /// </summary>
        public string MarketStaff { get; set; } = string.Empty;
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : PackDoc.cs
 */
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 成品包装单据原型
    /// </summary>
    public class PackDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 关联质检单号
        /// </summary>
        public string RelateInspectNo { get; set; } = string.Empty;
 
        /// <summary>
        /// 礼盒档次:高端/标准/简易
        /// </summary>
        public string BoxLevel { get; set; } = string.Empty;
 
        /// <summary>
        /// 包装总件数
        /// </summary>
        public int PackTotal { get; set; }
 
        /// <summary>
        /// 包装员
        /// </summary>
        public string Packer { get; set; } = string.Empty;
 
        /// <summary>
        /// 商品条码
        /// </summary>
        public string BarCode { get; set; } = string.Empty;
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : ProductionDo.cs
 */
 
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 加工生产单据原型
    /// </summary>
    public class ProductionDo : BaseJewelryDocument
    {
        /// <summary>
        /// 关联设计图纸单号
        /// </summary>
        public string RelateDraftNo { get; set; } = string.Empty;
 
        /// <summary>
        /// 生产批次号
        /// </summary>
        public int BatchNo { get; set; }
 
        /// <summary>
        /// 计划生产数量
        /// </summary>
        public int ProduceQty { get; set; }
 
        /// <summary>
        /// 生产车间
        /// </summary>
        public string Workshop { get; set; } = string.Empty;
 
        /// <summary>
        /// 工艺师
        /// </summary>
        public string Craftsman { get; set; } = string.Empty;
 
        /// <summary>
        /// 计划完工时间
        /// </summary>
        public DateTime PlanFinish { get; set; }
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : QualityInspectDoc.cs
 */
 
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 成品质检单据原型
    /// </summary>
    public class QualityInspectDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 关联生产批次单号
        /// </summary>
        public string RelateProductionNo { get; set; } = string.Empty;
 
        /// <summary>
        /// 合格数量
        /// </summary>
        public int PassQty { get; set; }
 
        /// <summary>
        /// 不良品数量
        /// </summary>
        public int DefectQty { get; set; }
 
        /// <summary>
        /// 质检员
        /// </summary>
        public string Inspector { get; set; } = string.Empty;
 
        /// <summary>
        /// 不良备注
        /// </summary>
        public string DefectRemark { get; set; } = string.Empty;
 
        /// <summary>
        /// 整批是否放行
        /// </summary>
        public bool BatchPass { get; set; }
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : RawMaterialPurchaseDoc.cs
 */
 
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 原料采购核验单据原型
    /// </summary>
    public class RawMaterialPurchaseDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 原料类型:足金/铂金/钻石/彩宝
        /// </summary>
        public string MaterialType { get; set; } = string.Empty;
 
        /// <summary>
        /// 原料重量(g)
        /// </summary>
        public decimal Weight { get; set; }
 
        /// <summary>
        /// 单价
        /// </summary>
        public decimal UnitPrice { get; set; }
 
        /// <summary>
        /// 采购总金额
        /// </summary>
        public decimal TotalCost => Weight * UnitPrice;
 
        /// <summary>
        /// 供应商名称
        /// </summary>
        public string Supplier { get; set; } = string.Empty;
 
        /// <summary>
        /// 原料质检是否通过
        /// </summary>
        public bool QualityPass { get; set; }
 
        /// <summary>
        /// 原料检测报告编号
        /// </summary>
        public string InspectionNo { get; set; } = string.Empty;
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : SaleDoc.cs
 */
 
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 门店销售单据原型
    /// </summary>
    public class SaleDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 客户姓名
        /// </summary>
        public string CustomerName { get; set; } = string.Empty;
 
        /// <summary>
        /// 客户电话
        /// </summary>
        public string CustomerPhone { get; set; } = string.Empty;
 
        /// <summary>
        /// 销售总金额
        /// </summary>
        public decimal SaleTotal { get; set; }
 
        /// <summary>
        /// 销售顾问
        /// </summary>
        public string Salesman { get; set; } = string.Empty;
 
        /// <summary>
        /// 关联营销活动单号
        /// </summary>
        public string RelatePromoNo { get; set; } = string.Empty;
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : TrainingRecordDoc.cs
 */
 
 
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Business.Documents
{
    /// <summary>
    /// 员工培训记录单据原型
    /// </summary>
    public class TrainingRecordDoc : BaseJewelryDocument
    {
        /// <summary>
        /// 培训主题
        /// </summary>
        public string TrainTheme { get; set; } = string.Empty;
 
        /// <summary>
        /// 培训讲师
        /// </summary>
        public string Trainer { get; set; } = string.Empty;
 
        /// <summary>
        /// 参训员工工号集合
        /// </summary>
        public List<string> TraineeIds { get; set; } = new List<string>();
 
        /// <summary>
        /// 培训开始时间
        /// </summary>
        public DateTime TrainStart { get; set; }
 
        /// <summary>
        /// 培训结束时间
        /// </summary>
        public DateTime TrainEnd { get; set; }
 
        /// <summary>
        /// 培训成本
        /// </summary>
        public decimal TrainCost { get; set; }
    }
}
 
cs 复制代码
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : LogTemplateConstant.cs
 */
 
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Core.Constants
{
    /// <summary>
    /// 日志模板常量,统一控制台+文件输出,保证内容完全一致
    /// </summary>
    public static class LogTemplateConstant
    {
        /// <summary>
        /// 日志格式化模板(控制台、文件共用)
        /// </summary>
        public const string Template = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{Level:u3}] {Emoji} [{Category}] {Message}{NewLine}{Exception}";
 
        /// <summary>
        /// 时间戳格式
        /// </summary>
        public const string TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff";
 
        ///
        /// <summary>日期文件夹格式
        /// </summary>
        public const string DateFolderFormat = "yyyy-MM-dd";
 
        /// <summary>
        /// 文件路径模板 Logs/2026-07-10/app-{Level}.log
        /// </summary>
        public const string FilePathFormat = "{Date:" + DateFolderFormat + "}/app-{Level}.log";
 
        /// <summary>
        /// 日志根目录
        /// </summary>
        public const string LogBasePath = "Logs";
 
        /// <summary>
        /// 自动清理过期日志天数
        /// </summary>
        public const int RetainLogDays = 30;
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : JewelryFileLogExtension.cs
 */
 
using Microsoft.Extensions.Logging;
using PrototypePattern.Core.Constants;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Display;
using System;
using System.Collections.Generic;
using System.IO;
 
namespace PrototypePattern.Core.Extensions.Logging
{
 
 
    /// <summary>
    ///
    /// </summary>
    public static class JewelryFileLogExtension
    {
        private static readonly Dictionary<LogLevel, string> _logLevelEmojis = new()
        {
            { LogLevel.Debug, "🔍" },
            { LogLevel.Information, "ℹ️" },
            { LogLevel.Warning, "⚠️" },
            { LogLevel.Error, "❌" },
            { LogLevel.Critical, "🔥" }
        };
 
        public static ILoggingBuilder AddEnterpriseJewelryLog(this ILoggingBuilder builder)
        {
            string logRoot = Path.Combine(Directory.GetCurrentDirectory(), LogTemplateConstant.LogBasePath);
            Directory.CreateDirectory(logRoot);
 
            var logLevelMap = new Dictionary<LogEventLevel, LogLevel>
            {
                { LogEventLevel.Verbose, LogLevel.Trace },
                { LogEventLevel.Debug, LogLevel.Debug },
                { LogEventLevel.Information, LogLevel.Information },
                { LogEventLevel.Warning, LogLevel.Warning },
                { LogEventLevel.Error, LogLevel.Error },
                { LogEventLevel.Fatal, LogLevel.Critical }
            };
 
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("System", LogEventLevel.Warning)
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Console(outputTemplate: FormatTemplate(LogTemplateConstant.Template))
                .WriteTo.File(
                    path: Path.Combine(logRoot, "app-.log"),
                    outputTemplate: FormatTemplate(LogTemplateConstant.Template),
                    rollingInterval: RollingInterval.Day,
                    retainedFileCountLimit: LogTemplateConstant.RetainLogDays,
                    fileSizeLimitBytes: 1000000,
                    rollOnFileSizeLimit: true,
                    restrictedToMinimumLevel: LogEventLevel.Debug)
                .CreateLogger();
 
            builder.ClearProviders();
            builder.AddSerilog(dispose: true);
 
            return builder;
        }
 
        private static string FormatTemplate(string template)
        {
            return template.Replace("{Emoji}", "{Level:u3}")
                          .Replace("{Category}", "{SourceContext}");
        }
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : BaseJewelryDocument.cs
 */
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
 
namespace PrototypePattern.Core.Prototype
{
    /// <summary>
    /// 所有业务单据原型基类,统一基础字段与通用深拷贝逻辑
    /// </summary>
    public abstract class BaseJewelryDocument : IJewelryPrototype
    {
        /// <summary>
        /// 单据唯一编号
        /// </summary>
        public string DocNo { get; set; } = string.Empty;
 
        /// <summary>
        /// 所属业务模块名称
        /// </summary>
        public string BizModule { get; set; } = string.Empty;
 
        /// <summary>
        /// 操作人名称
        /// </summary>
        public string Operator { get; set; } = string.Empty;
 
        /// <summary>
        /// 单据创建时间
        /// </summary>
        public DateTime CreateTime { get; set; } = DateTime.Now;
 
        public virtual IJewelryPrototype Clone()
        {
            return (IJewelryPrototype)MemberwiseClone();
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public virtual IJewelryPrototype DeepClone()
        {
            var jsonOpt = new JsonSerializerOptions { WriteIndented = false };
            string json = JsonSerializer.Serialize(this, jsonOpt);
            return (IJewelryPrototype)JsonSerializer.Deserialize(json, GetType())!;
        }
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : IJewelryPrototype.cs
 */
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Core.Prototype
{
    /// <summary>
    /// 珠宝业务单据原型顶层接口,统一拷贝规范
    /// </summary>
    public interface IJewelryPrototype
    {
        /// <summary>
        /// 浅拷贝:引用类型共用实例
        /// </summary>
        IJewelryPrototype Clone();
 
        /// <summary>
        /// 深拷贝:所有嵌套对象全新实例,多线程隔离安全
        /// </summary>
        IJewelryPrototype DeepClone();
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : ConcurrentPrototypePool.cs
 */
 
 
using Microsoft.Extensions.Logging;
using PrototypePattern.Core.Prototype;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Core.ThreadSafe
{
    /// <summary>
    /// 线程安全原型模板池,并发读写无锁,全局缓存空白单据模板
    /// </summary>
    public class ConcurrentPrototypePool
    {
        private readonly ILogger<ConcurrentPrototypePool> _logger;
        private readonly ConcurrentDictionary<string, BaseJewelryDocument> _templateStore = new();
 
        public ConcurrentPrototypePool(ILogger<ConcurrentPrototypePool> logger)
        {
            _logger = logger;
        }
 
        /// <summary>
        /// 注册业务单据空白模板到缓存池(线程安全)
        /// </summary>
        public void RegisterTemplate(string bizKey, BaseJewelryDocument templateDoc)
        {
            if (_templateStore.ContainsKey(bizKey))
            {
                _logger.LogWarning("⚠️ 业务模板 {BizKey} 已存在,覆盖原有模板", bizKey);
            }
            _templateStore.AddOrUpdate(bizKey, templateDoc, (k, old) => templateDoc);
            _logger.LogDebug("🔍 注册业务原型模板成功 Key:{BizKey} Module:{Module}", bizKey, templateDoc.BizModule);
        }
 
        /// <summary>
        /// 根据业务标识深拷贝全新单据
        /// </summary>
        public T GetCloneDocument<T>(string bizKey) where T : BaseJewelryDocument
        {
            if (!_templateStore.TryGetValue(bizKey, out var template))
            {
                _logger.LogError("❌ 原型池不存在业务模板 Key:{BizKey}", bizKey);
                throw new KeyNotFoundException($"业务原型模板[{bizKey}]未注册");
            }
 
            var newDoc = (T)template.DeepClone();
            newDoc.DocNo = GenerateUniqueDocNo(bizKey);
            newDoc.CreateTime = DateTime.Now;
            _logger.LogDebug("✅ 克隆生成单据 模块:{Module} 单号:{DocNo}", newDoc.BizModule, newDoc.DocNo);
            return newDoc;
        }
 
        /// <summary>
        /// 获取已注册模板总数
        /// </summary>
        public int GetRegisteredTemplateCount()
        {
            return _templateStore.Count;
        }
 
        /// <summary>
        /// 生成全局唯一业务单号
        /// </summary>
        private string GenerateUniqueDocNo(string bizKey)
        {
            return $"{bizKey}_{DateTime.Now:yyyyMMddHHmmss}_{Random.Shared.Next(100, 999)}";
        }
    }
}
 
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : JewelryTemplateInitializer.cs
 */
 
 
using Microsoft.Extensions.Logging;
using PrototypePattern.Business.Documents;
using PrototypePattern.Core.ThreadSafe;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Workflow.Pool
{
    /// <summary>
    /// 业务原型模板初始化器:统一注册12大业务空白单据到线程安全原型池
    /// </summary>
    public class JewelryTemplateInitializer
    {
        private readonly ConcurrentPrototypePool _prototypePool;
        private readonly ILogger<JewelryTemplateInitializer> _logger;
 
        public JewelryTemplateInitializer(ConcurrentPrototypePool prototypePool, ILogger<JewelryTemplateInitializer> logger)
        {
            _prototypePool = prototypePool;
            _logger = logger;
        }
 
        /// <summary>
        /// 一次性加载全部业务模板,程序启动执行一次
        /// </summary>
        public void LoadAllBusinessTemplates()
        {
            _prototypePool.RegisterTemplate("RawMaterial", new RawMaterialPurchaseDoc { BizModule = "原料采购核验" });
            _prototypePool.RegisterTemplate("Design", new DesignDraftDoc { BizModule = "设计制图" });
            _prototypePool.RegisterTemplate("Production", new ProductionDoc { BizModule = "加工生产" });
            _prototypePool.RegisterTemplate("Quality", new QualityInspectDoc { BizModule = "质检" });
            _prototypePool.RegisterTemplate("Pack", new PackDoc { BizModule = "包装" });
            _prototypePool.RegisterTemplate("Logistics", new LogisticsDoc { BizModule = "物流" });
            _prototypePool.RegisterTemplate("Finance", new FinanceBillDoc { BizModule = "财务" });
            _prototypePool.RegisterTemplate("Marketing", new MarketingPromoDoc { BizModule = "营销推广" });
            _prototypePool.RegisterTemplate("Sale", new SaleDoc { BizModule = "业务销售" });
            _prototypePool.RegisterTemplate("Hr", new HrAdminDoc { BizModule = "人事行政" });
            _prototypePool.RegisterTemplate("IT", new ItOpsDoc { BizModule = "IT运维" });
            _prototypePool.RegisterTemplate("Train", new TrainingRecordDoc { BizModule = "员工培训" });
 
            int count = _prototypePool.GetRegisteredTemplateCount();
            _logger.LogInformation("🏭 全部业务原型模板加载完成,共注册 {Count} 套单据模板", count);
        }
    }
}
 
 
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : JewelryBusinessFlowScheduler.cs
 */
 
using Microsoft.Extensions.Logging;
using PrototypePattern.Business.Documents;
using PrototypePattern.Core.Prototype;
using PrototypePattern.Core.ThreadSafe;
using System;
using System.Collections.Generic;
using System.Text;
 
namespace PrototypePattern.Workflow.Scheduler
{
    /// <summary>
    /// 珠宝全业务流程调度器:仅负责流程编排、日志埋点,不持有模板存储,依赖原型池获取克隆单据
    /// </summary>
    public class JewelryBusinessFlowScheduler
    {
        private readonly ILogger<JewelryBusinessFlowScheduler> _logger;
        private readonly ConcurrentPrototypePool _prototypePool;
 
        public JewelryBusinessFlowScheduler(ILogger<JewelryBusinessFlowScheduler> logger, ConcurrentPrototypePool prototypePool)
        {
            _logger = logger;
            _prototypePool = prototypePool;
            _logger.LogDebug("🔍 业务流程调度器实例化完成");
        }
 
        /// <summary>
        /// 原型模式对外暴露:克隆全新业务单据
        /// </summary>
        public T CreateDocument<T>(string bizKey) where T : BaseJewelryDocument
        {
            return _prototypePool.GetCloneDocument<T>(bizKey);
        }
 
        /// <summary>
        /// 完整珠宝产销全链路异步流程,支持多线程高并发执行
        /// </summary>
        public async Task ExecuteFullProductionSaleFlowAsync(string operatorName, CancellationToken cancelToken)
        {
            try
            {
                _logger.LogInformation("🚀 启动完整珠宝全业务流程,操作员:{Operator}", operatorName);
 
                // 1.原料采购核验
                var rawDoc = CreateDocument<RawMaterialPurchaseDoc>("RawMaterial");
                rawDoc.Operator = operatorName;
                rawDoc.MaterialType = "足金999";
                rawDoc.Weight = 600;
                rawDoc.UnitPrice = 585;
                rawDoc.Supplier = "深圳黄金原料供应商";
                rawDoc.QualityPass = true;
                rawDoc.InspectionNo = $"INS{Random.Shared.Next(10000, 99999)}";
                _logger.LogInformation("📥 原料入库核验完成,采购总金额:{Total:C}", rawDoc.TotalCost);
 
                // 2.设计制图
                var designDoc = CreateDocument<DesignDraftDoc>("Design");
                designDoc.Operator = operatorName;
                designDoc.StyleName = "古法福字手镯";
                designDoc.Designer = "刘设计师";
                designDoc.CustomerConfirm = true;
                _logger.LogInformation("🎨 款式设计定稿:{Style}", designDoc.StyleName);
 
                // 3.加工生产
                var prodDoc = CreateDocument<ProductionDoc>("Production");
                prodDoc.Operator = operatorName;
                prodDoc.RelateDraftNo = designDoc.DocNo;
                prodDoc.ProduceQty = 150;
                prodDoc.Workshop = "黄金一号车间";
                prodDoc.PlanFinish = DateTime.Now.AddDays(3);
                _logger.LogInformation("⚒️ 生产批次创建,计划产量:{Qty}", prodDoc.ProduceQty);
 
                // 4.成品质检
                var qcDoc = CreateDocument<QualityInspectDoc>("Quality");
                qcDoc.Operator = operatorName;
                qcDoc.RelateProductionNo = prodDoc.DocNo;
                qcDoc.PassQty = 147;
                qcDoc.DefectQty = 3;
                qcDoc.BatchPass = true;
                _logger.LogWarning("🔎 批次质检完成,合格{Pass}件,不良{Defect}件", qcDoc.PassQty, qcDoc.DefectQty);
 
                // 5.成品包装
                var packDoc = CreateDocument<PackDoc>("Pack");
                packDoc.Operator = operatorName;
                packDoc.RelateInspectNo = qcDoc.DocNo;
                packDoc.PackTotal = qcDoc.PassQty;
                _logger.LogInformation("🎁 成品礼盒包装完成,合计{Num}件", packDoc.PackTotal);
 
                // 6.物流发货
                var logDoc = CreateDocument<LogisticsDoc>("Logistics");
                logDoc.Operator = operatorName;
                logDoc.RelatePackNo = packDoc.DocNo;
                logDoc.Express = "珠宝安保专线物流";
                logDoc.TrackNo = $"JL{Random.Shared.Next(1000000, 9999999)}";
                logDoc.ShipTime = DateTime.Now;
                _logger.LogInformation("🚚 物流已发出,运单号:{Track}", logDoc.TrackNo);
 
                // 7.财务入账
                var finDoc = CreateDocument<FinanceBillDoc>("Finance");
                finDoc.Operator = operatorName;
                finDoc.RelateBizNo = rawDoc.DocNo;
                finDoc.BillType = "原料采购支出";
                finDoc.Amount = rawDoc.TotalCost;
                finDoc.Audited = true;
                _logger.LogInformation("💰 财务单据审核完成,金额:{Amt:C}", finDoc.Amount);
 
                // 8.营销活动
                var marketDoc = CreateDocument<MarketingPromoDoc>("Marketing");
                marketDoc.Operator = operatorName;
                marketDoc.PromoName = "七夕黄金满减活动";
                marketDoc.DiscountRate = 0.9m;
                _logger.LogInformation("📢 营销活动创建:{Promo}", marketDoc.PromoName);
 
                // 9.门店销售
                var saleDoc = CreateDocument<SaleDoc>("Sale");
                saleDoc.Operator = operatorName;
                saleDoc.RelatePromoNo = marketDoc.DocNo;
                saleDoc.SaleTotal = 32800;
                saleDoc.CustomerName = "张女士";
                _logger.LogInformation("🛒 销售成交,客户:{Cust} 成交额:{Sale:C}", saleDoc.CustomerName, saleDoc.SaleTotal);
 
                // 10.人事行政记录
                var hrDoc = CreateDocument<HrAdminDoc>("Hr");
                hrDoc.Operator = operatorName;
                hrDoc.StaffName = operatorName;
                hrDoc.OperateType = "日常业务操作记录";
                _logger.LogDebug("👔 人事操作日志生成");
 
                // 11.IT系统巡检
                var itDoc = CreateDocument<ItOpsDoc>("IT");
                itDoc.Operator = operatorName;
                itDoc.DeviceSystem = "珠宝ERP管理系统";
                itDoc.Fixed = true;
                _logger.LogDebug("💻 IT运维巡检完成,系统无故障");
 
                // 12.员工培训记录
                var trainDoc = CreateDocument<TrainingRecordDoc>("Train");
                trainDoc.Operator = operatorName;
                trainDoc.TrainTheme = "新款珠宝销售话术培训";
                trainDoc.TraineeIds.AddRange(new[] { "S001", "S002", "S003" });
                _logger.LogInformation("📚 员工培训记录创建完成");
 
                _logger.LogInformation("✅ 珠宝全业务流程执行完毕,操作员:{Op}", operatorName);
                await Task.Delay(5, cancelToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "🔥 业务流程执行异常,操作员:{Operator}", operatorName);
                throw;
            }
        }
    }
}

调用:

cs 复制代码
/*
 # encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:创建型模式 Prototype Pattern 原型模式
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : vs2026 c# .net 10
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/07/04 22:16
# User      :  geovindu
# Product   : Visual Studio 2026
# Project   : CSharpDesignPattern
# File      : PrototypeBll.cs
 */
 
using System;
using System.Collections.Generic;
using System.Text;
using PrototypePattern.Core.Extensions.Logging;
using PrototypePattern.Core.ThreadSafe;
using PrototypePattern.Workflow.Pool;
using PrototypePattern.Workflow.Scheduler;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
 
namespace BLL
{
 
    public class PrototypeBll
    {
        public async void Demo()
        {
            // 1.构建DI主机
            var host = Host.CreateDefaultBuilder()
                .ConfigureLogging((context, loggingBuilder) =>
                {
                    loggingBuilder.ClearProviders();
                    // 加载企业级统一日志(文件+控制台输出完全一致)
                    loggingBuilder.AddEnterpriseJewelryLog();
                })
                .ConfigureServices(services =>
                {
                    // 线程安全原型池(单例全局唯一)
                    services.AddSingleton<ConcurrentPrototypePool>();
                    // 模板初始化器
                    services.AddScoped<JewelryTemplateInitializer>();
                    // 业务流程调度器
                    services.AddTransient<JewelryBusinessFlowScheduler>();
                })
                .Build();
 
            // 2.启动时加载全部业务原型模板
            using var scope = host.Services.CreateScope();
            var serviceProvider = scope.ServiceProvider;
            var templateInit = serviceProvider.GetRequiredService<JewelryTemplateInitializer>();
            templateInit.LoadAllBusinessTemplates();
 
            // 3.获取流程调度器,模拟高并发多线程执行业务流程
            var scheduler = host.Services.GetRequiredService<JewelryBusinessFlowScheduler>();
            var cts = new CancellationTokenSource();
            var taskList = new List<Task>();
            string[] operatorList = { "王店长", "李工艺师", "陈运营" };
 
            foreach (var op in operatorList)
            {
                taskList.Add(scheduler.ExecuteFullProductionSaleFlowAsync(op, cts.Token));
            }
 
            // 等待全部并发流程执行完成
            await Task.WhenAll(taskList);
 
            // 输出提示
            Console.WriteLine(Environment.NewLine + "==============================");
            Console.WriteLine("全部高并发业务流程执行完成!");
            Console.WriteLine("日志目录结构:Logs/yyyy-MM-dd/");
            Console.WriteLine("分级日志文件:app-debug.log / app-info.log / app-warn.log / app-error.log");
            Console.WriteLine("控制台输出与日志文件内容、模板、Emoji完全一致");
            Console.WriteLine("==============================");
 
            // 释放资源
            await host.StopAsync();
        }
    }
}

输出:

相关推荐
ttod_qzstudio1 小时前
【软考设计模式】组合模式:“部分-整体“层次结构与树形对象统一操作精讲
设计模式·组合模式
Listen·Rain2 小时前
Springboot整合Ollama实现调用本地多模型
java·spring boot·后端
天天进步20152 小时前
Python全栈项目--校园食堂点餐与推荐系统
开发语言·python
aaPIXa6222 小时前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
张三丰22 小时前
Agent 不只是聊天框:用 ArkUI 做一个鸿蒙任务工作台
后端
eybk2 小时前
写一个可以编制pdf文件的python程序
开发语言·python·pdf
卷无止境2 小时前
从Python的cryptography库出发,从零开始理解密码学,到构建零信任网络
后端·python
Augustzero2 小时前
`co_await` 按下暂停键之后:从零看懂 C++20 协程
c++·后端
cui_ruicheng2 小时前
Python从入门到实战(八):封装、多态与抽象类
开发语言·python