一、引言
本节介绍工厂方法模式(Factory Method Pattern)在珠宝制造业务系统中的实际应用背景,说明为什么需要将产品线创建逻辑与业务处理解耦,以及本文将要展示的 Rust 实现思路。
二、核心概念
本节讲解工厂方法模式的核心思想,包括抽象工厂、具体工厂、产品接口与具体产品之间的关系,以及该模式在创建型模式中的定位。
- 模式定义与结构:说明工厂方法模式的定义、参与者角色以及类图结构。
- 适用场景:分析在珠宝多产品线(黄金、钻石、彩色宝石、铂金)场景下使用工厂方法模式的原因。
- 与简单工厂的区别:对比工厂方法模式与简单工厂在扩展性和职责划分上的差异。
三、Rust 实现要点
本节围绕 Rust 语言特性,介绍如何用 trait、泛型和关联常量实现工厂方法模式,并说明错误处理与线程安全设计。
- trait 抽象设计:讲解 ProductLineFactory 与 ProductLineInfo 两个核心 trait 的设计思路。
- 泛型与关联常量:说明如何通过泛型参数和关联常量为不同产品线提供静态配置。
- 错误处理与并发:介绍 JewelryError 统一错误类型以及线程池、消息队列在订单处理中的应用。
四、实战示例
本节给出完整的 Rust 代码示例,展示从领域模型、工厂实现到订单处理服务的完整链路,并演示黄金、钻石、彩色宝石、铂金四条产品线的调用方式。
五、总结
本节总结工厂方法模式在 Rust 珠宝业务系统中的落地效果,回顾模式带来的扩展性收益,并给出后续优化方向。
项目结构:

rust
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Factory Method Pattern 工厂方法模式 创建型模式 Creational Patterns
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:43
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : errors.rs
use thiserror::Error;
/// 珠宝业务领域错误类型
/// 覆盖所有业务模块可能出现的错误场景
#[derive(Debug, Error)]
pub enum JewelryError {
#[error("原料核验失败: {0}")]
MaterialVerifyFailed(String),
#[error("设计制图失败: {0}")]
DesignFailed(String),
#[error("加工生产失败: {0}")]
ManufactureFailed(String),
#[error("质检失败: {0}")]
QualityInspectFailed(String),
#[error("包装失败: {0}")]
PackFailed(String),
#[error("物流失败: {0}")]
LogisticsFailed(String),
#[error("财务处理失败: {0}")]
FinanceFailed(String),
#[error("营销失败: {0}")]
MarketingFailed(String),
#[error("业务订单失败: {0}")]
BusinessOrderFailed(String),
#[error("人事行政失败: {0}")]
HrAdminFailed(String),
#[error("IT运维失败: {0}")]
ItOpsFailed(String),
#[error("培训失败: {0}")]
TrainingFailed(String),
#[error("未知业务模块: {0}")]
UnknownModule(String),
#[error("系统内部错误: {0}")]
InternalError(String),
#[error("重试次数耗尽: {0}")]
RetryExhausted(String),
}
/// 统一结果类型别名
pub type JewelryResult<T> = Result<T, JewelryError>;
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:44
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : factory.rs
use crate::domain::errors::{JewelryError, JewelryResult};
use crate::domain::models::*;
use crate::domain::traits::*;
use chrono::Utc;
use std::marker::PhantomData;
// ==================== 抽象工厂trait ====================
pub trait ProductLineFactory: Send + Sync {
// 制造相关
fn create_manufacturer(&self) -> Box<dyn Manufacturer>;
fn create_design_draftsman(&self) -> Box<dyn DesignDraftsman>;
fn create_material_verifier(&self) -> Box<dyn MaterialVerifier>;
// 质检相关
fn create_quality_inspector(&self) -> Box<dyn QualityInspector>;
// 物流相关
fn create_logistics_provider(&self) -> Box<dyn LogisticsProvider>;
// 财务相关
fn create_finance_processor(&self) -> Box<dyn FinanceProcessor>;
// 营销相关
fn create_marketing_promoter(&self) -> Box<dyn MarketingPromoter>;
// 业务订单相关
fn create_business_order_processor(&self) -> Box<dyn BusinessOrderProcessor>;
// HR相关
fn create_hr_administrator(&self) -> Box<dyn HrAdministrator>;
// IT相关
fn create_it_operator(&self) -> Box<dyn ItOperator>;
// 培训相关
fn create_training_provider(&self) -> Box<dyn TrainingProvider>;
// 克隆工厂(用于线程传递)
fn clone_factory(&self) -> Box<dyn ProductLineFactory>;
}
// ==================== 产品线配置 ====================
/// 产品线静态配置,用于参数化各产品线的具体角色实现
pub trait ProductLineInfo: Send + Sync {
const MATERIAL: MaterialType;
const LINE_NAME: &'static str;
const AREA: &'static str;
const STEPS: &'static [&'static str];
const PURITY_MIN: f64;
const PURITY_MAX: f64;
const PURITY_UNIT: &'static str;
const STANDARD: &'static str;
const CARRIER: &'static str;
const DELIVERY_PREFIX: &'static str;
const FINANCE_SYSTEM: &'static str;
const INVOICE_PREFIX: &'static str;
const MARKETING_CHANNEL: &'static str;
const BUSINESS_SYSTEM: &'static str;
const ORDER_PREFIX: &'static str;
const HR_SYSTEM: &'static str;
const SHIFT_PREFIX: &'static str;
const OPS_PLATFORM: &'static str;
const CHECK_PREFIX: &'static str;
const TRAINING_PLATFORM: &'static str;
const COURSE_PREFIX: &'static str;
const TRAINING_SUBJECT: &'static str;
}
// ==================== 通用角色实现 ====================
#[allow(dead_code)]
pub struct ManufacturerImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct DesignDraftsmanImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct MaterialVerifierImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct QualityInspectorImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct LogisticsProviderImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct FinanceProcessorImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct MarketingPromoterImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct BusinessOrderProcessorImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct HrAdministratorImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct ItOperatorImpl<L: ProductLineInfo>(pub PhantomData<L>);
pub struct TrainingProviderImpl<L: ProductLineInfo>(pub PhantomData<L>);
impl<L: ProductLineInfo> Manufacturer for ManufacturerImpl<L> {
fn start_production(&self, work_order: &WorkOrder) -> JewelryResult<String> {
Ok(format!(
"{}生产线已开始生产工单: {}",
L::LINE_NAME, work_order.work_order_no
))
}
fn get_process_steps(&self) -> Vec<String> {
L::STEPS.iter().map(|s| s.to_string()).collect()
}
fn production_line_name(&self) -> &str {
L::LINE_NAME
}
}
impl<L: ProductLineInfo> DesignDraftsman for DesignDraftsmanImpl<L> {
fn render_3d_model(&self, spec: &DesignSpec) -> JewelryResult<String> {
if spec.cad_file_url.ends_with(".stl") || spec.cad_file_url.ends_with(".obj") {
Ok(spec.cad_file_url.clone())
} else {
Err(JewelryError::DesignFailed(format!(
"{}产品设计仅支持STL或OBJ格式",
L::AREA
)))
}
}
fn check_cad_standard(&self, cad_file_url: &str) -> JewelryResult<bool> {
Ok(cad_file_url.ends_with(".stl") || cad_file_url.ends_with(".obj"))
}
fn design_tool_name(&self) -> &str {
"JewelCAD"
}
}
impl<L: ProductLineInfo> MaterialVerifier for MaterialVerifierImpl<L> {
fn verify_batch(&self, batch: &MaterialBatch) -> JewelryResult<String> {
if batch.material_type != L::MATERIAL {
return Err(JewelryError::MaterialVerifyFailed(format!(
"材料类型不匹配:期望{}",
L::AREA
)));
}
if batch.purity_grade < L::PURITY_MIN || batch.purity_grade > L::PURITY_MAX {
return Err(JewelryError::MaterialVerifyFailed(format!(
"{}纯度/等级不达标:{},要求{}-{}{}",
L::AREA, batch.purity_grade, L::PURITY_MIN, L::PURITY_MAX, L::PURITY_UNIT
)));
}
Ok(format!("{}批次核验通过", L::AREA))
}
fn supported_material_type(&self) -> MaterialType {
L::MATERIAL
}
fn verification_standard(&self) -> &str {
L::STANDARD
}
}
impl<L: ProductLineInfo> QualityInspector for QualityInspectorImpl<L> {
fn inspect_product(&self, work_order_no: &str, inspector_id: &str) -> JewelryResult<QualityReport> {
Ok(QualityReport {
report_id: generate_id("QR"),
work_order_no: work_order_no.to_string(),
inspector_id: inspector_id.to_string(),
passed: true,
standard: L::STANDARD.to_string(),
report_time: Utc::now(),
})
}
fn quality_standard(&self) -> &str {
L::STANDARD
}
fn inspection_equipment(&self) -> &str {
"光谱检测仪"
}
}
impl<L: ProductLineInfo> LogisticsProvider for LogisticsProviderImpl<L> {
fn create_delivery(&self, order: &CustomerOrder, insured_value: f64) -> JewelryResult<DeliveryOrder> {
Ok(DeliveryOrder {
tracking_no: format!("{}-{}", L::DELIVERY_PREFIX, generate_id("DL")),
order_id: order.order_id.clone(),
carrier: L::CARRIER.to_string(),
insured_value,
shipped_at: Utc::now(),
})
}
fn carrier_name(&self) -> &str {
L::CARRIER
}
}
impl<L: ProductLineInfo> FinanceProcessor for FinanceProcessorImpl<L> {
fn generate_invoice(&self, order: &CustomerOrder, tax_rate: f64) -> JewelryResult<Invoice> {
Ok(Invoice {
invoice_no: generate_id(L::INVOICE_PREFIX),
order_id: order.order_id.clone(),
amount: order.amount,
tax_rate,
issued_at: Utc::now(),
})
}
fn finance_system_name(&self) -> &str {
L::FINANCE_SYSTEM
}
}
impl<L: ProductLineInfo> MarketingPromoter for MarketingPromoterImpl<L> {
fn create_promotion_material(&self, campaign: &MarketingCampaign, sku: &str) -> JewelryResult<String> {
Ok(format!(
"【{}】{}特惠活动,SKU: {},活动时间:{} 至 {}。",
campaign.theme, L::AREA, sku, campaign.start_date, campaign.end_date
))
}
fn marketing_channel(&self) -> &str {
L::MARKETING_CHANNEL
}
}
impl<L: ProductLineInfo> BusinessOrderProcessor for BusinessOrderProcessorImpl<L> {
fn create_order(&self, customer_id: &str, _sku: &str, amount: f64) -> JewelryResult<CustomerOrder> {
Ok(CustomerOrder {
order_id: generate_id(L::ORDER_PREFIX),
customer_id: customer_id.to_string(),
amount,
status: OrderStatus::Created,
created_at: Utc::now(),
})
}
fn business_system_name(&self) -> &str {
L::BUSINESS_SYSTEM
}
}
impl<L: ProductLineInfo> HrAdministrator for HrAdministratorImpl<L> {
fn arrange_shift(&self, department: &str, employee_id: &str) -> JewelryResult<EmployeeShift> {
Ok(EmployeeShift {
shift_id: generate_id(L::SHIFT_PREFIX),
department: department.to_string(),
employee_id: employee_id.to_string(),
shift_type: ShiftType::Morning,
})
}
fn hr_system_name(&self) -> &str {
L::HR_SYSTEM
}
}
impl<L: ProductLineInfo> ItOperator for ItOperatorImpl<L> {
fn system_health_check(&self) -> JewelryResult<SystemCheckReport> {
Ok(SystemCheckReport {
check_id: generate_id(L::CHECK_PREFIX),
system_name: format!("{}生产线MES系统", L::LINE_NAME),
status: SystemStatus::Healthy,
check_time: Utc::now(),
})
}
fn ops_platform_name(&self) -> &str {
L::OPS_PLATFORM
}
}
impl<L: ProductLineInfo> TrainingProvider for TrainingProviderImpl<L> {
fn get_training_course(&self, role: &str) -> JewelryResult<TrainingCourse> {
Ok(TrainingCourse {
course_id: generate_id(L::COURSE_PREFIX),
course_name: format!("{}岗位{}工艺培训课程", role, L::AREA),
target_role: role.to_string(),
material_url: format!("https://training.internal/{}.pdf", L::AREA),
})
}
fn training_platform_name(&self) -> &str {
L::TRAINING_PLATFORM
}
}
// ==================== 具体产品线 ====================
pub struct GoldProductLineFactory;
pub struct DiamondProductLineFactory;
pub struct ColoredGemstoneProductLineFactory;
pub struct PlatinumProductLineFactory;
struct GoldLine;
struct DiamondLine;
struct ColoredGemstoneLine;
struct PlatinumLine;
impl ProductLineInfo for GoldLine {
const MATERIAL: MaterialType = MaterialType::Gold;
const LINE_NAME: &'static str = "黄金";
const AREA: &'static str = "黄金";
const STEPS: &'static [&'static str] = &["熔金", "压延", "拉丝", "成型", "最终检验"];
const PURITY_MIN: f64 = 99.0;
const PURITY_MAX: f64 = 99.99;
const PURITY_UNIT: &'static str = "%";
const STANDARD: &'static str = "GB/T 18043-2013";
const CARRIER: &'static str = "顺丰保价专递";
const DELIVERY_PREFIX: &'static str = "GD";
const FINANCE_SYSTEM: &'static str = "金蝶财务系统";
const INVOICE_PREFIX: &'static str = "GI";
const MARKETING_CHANNEL: &'static str = "天猫旗舰店";
const BUSINESS_SYSTEM: &'static str = "ERP订单系统";
const ORDER_PREFIX: &'static str = "GO";
const HR_SYSTEM: &'static str = "HR人力资源系统";
const SHIFT_PREFIX: &'static str = "GS";
const OPS_PLATFORM: &'static str = "Zabbix运维平台";
const CHECK_PREFIX: &'static str = "GIT";
const TRAINING_PLATFORM: &'static str = "在线培训平台";
const COURSE_PREFIX: &'static str = "GC";
const TRAINING_SUBJECT: &'static str = "黄金";
}
impl ProductLineInfo for DiamondLine {
const MATERIAL: MaterialType = MaterialType::Diamond;
const LINE_NAME: &'static str = "钻石";
const AREA: &'static str = "钻石";
const STEPS: &'static [&'static str] = &["原石分拣", "切割", "打磨", "抛光", "分级检验"];
const PURITY_MIN: f64 = 1.0;
const PURITY_MAX: f64 = 10.0;
const PURITY_UNIT: &'static str = "级";
const STANDARD: &'static str = "GIA钻石4C分级标准";
const CARRIER: &'static str = "顺丰保价专递";
const DELIVERY_PREFIX: &'static str = "DD";
const FINANCE_SYSTEM: &'static str = "金蝶财务系统";
const INVOICE_PREFIX: &'static str = "DI";
const MARKETING_CHANNEL: &'static str = "小红书";
const BUSINESS_SYSTEM: &'static str = "ERP订单系统";
const ORDER_PREFIX: &'static str = "DO";
const HR_SYSTEM: &'static str = "HR人力资源系统";
const SHIFT_PREFIX: &'static str = "DS";
const OPS_PLATFORM: &'static str = "Zabbix运维平台";
const CHECK_PREFIX: &'static str = "DIT";
const TRAINING_PLATFORM: &'static str = "在线培训平台";
const COURSE_PREFIX: &'static str = "DC";
const TRAINING_SUBJECT: &'static str = "钻石";
}
impl ProductLineInfo for ColoredGemstoneLine {
const MATERIAL: MaterialType = MaterialType::ColoredGemstone;
const LINE_NAME: &'static str = "彩色宝石";
const AREA: &'static str = "彩色宝石";
const STEPS: &'static [&'static str] = &["宝石分拣", "切割", "打磨", "抛光", "最终检验"];
const PURITY_MIN: f64 = 1.0;
const PURITY_MAX: f64 = 10.0;
const PURITY_UNIT: &'static str = "级";
const STANDARD: &'static str = "彩色宝石分级标准";
const CARRIER: &'static str = "顺丰保价专递";
const DELIVERY_PREFIX: &'static str = "CGD";
const FINANCE_SYSTEM: &'static str = "金蝶财务系统";
const INVOICE_PREFIX: &'static str = "CGI";
const MARKETING_CHANNEL: &'static str = "抖音直播";
const BUSINESS_SYSTEM: &'static str = "ERP订单系统";
const ORDER_PREFIX: &'static str = "CGO";
const HR_SYSTEM: &'static str = "HR人力资源系统";
const SHIFT_PREFIX: &'static str = "CGS";
const OPS_PLATFORM: &'static str = "Zabbix运维平台";
const CHECK_PREFIX: &'static str = "CGIT";
const TRAINING_PLATFORM: &'static str = "在线培训平台";
const COURSE_PREFIX: &'static str = "CGC";
const TRAINING_SUBJECT: &'static str = "彩色宝石";
}
impl ProductLineInfo for PlatinumLine {
const MATERIAL: MaterialType = MaterialType::Platinum;
const LINE_NAME: &'static str = "铂金";
const AREA: &'static str = "铂金";
const STEPS: &'static [&'static str] = &["铂金熔炼", "压延", "拉丝", "成型", "抛光", "最终检验"];
const PURITY_MIN: f64 = 95.0;
const PURITY_MAX: f64 = 99.99;
const PURITY_UNIT: &'static str = "%";
const STANDARD: &'static str = "GB/T 19719-2005";
const CARRIER: &'static str = "顺丰保价专递";
const DELIVERY_PREFIX: &'static str = "PD";
const FINANCE_SYSTEM: &'static str = "金蝶财务系统";
const INVOICE_PREFIX: &'static str = "PI";
const MARKETING_CHANNEL: &'static str = "天猫旗舰店";
const BUSINESS_SYSTEM: &'static str = "ERP订单系统";
const ORDER_PREFIX: &'static str = "PO";
const HR_SYSTEM: &'static str = "HR人力资源系统";
const SHIFT_PREFIX: &'static str = "PS";
const OPS_PLATFORM: &'static str = "Zabbix运维平台";
const CHECK_PREFIX: &'static str = "PIT";
const TRAINING_PLATFORM: &'static str = "在线培训平台";
const COURSE_PREFIX: &'static str = "PC";
const TRAINING_SUBJECT: &'static str = "铂金";
}
macro_rules! impl_product_line_factory {
($factory:ty, $line:ty) => {
impl ProductLineFactory for $factory {
fn create_manufacturer(&self) -> Box<dyn Manufacturer> {
Box::new(ManufacturerImpl::<$line>(PhantomData))
}
fn create_design_draftsman(&self) -> Box<dyn DesignDraftsman> {
Box::new(DesignDraftsmanImpl::<$line>(PhantomData))
}
fn create_material_verifier(&self) -> Box<dyn MaterialVerifier> {
Box::new(MaterialVerifierImpl::<$line>(PhantomData))
}
fn create_quality_inspector(&self) -> Box<dyn QualityInspector> {
Box::new(QualityInspectorImpl::<$line>(PhantomData))
}
fn create_logistics_provider(&self) -> Box<dyn LogisticsProvider> {
Box::new(LogisticsProviderImpl::<$line>(PhantomData))
}
fn create_finance_processor(&self) -> Box<dyn FinanceProcessor> {
Box::new(FinanceProcessorImpl::<$line>(PhantomData))
}
fn create_marketing_promoter(&self) -> Box<dyn MarketingPromoter> {
Box::new(MarketingPromoterImpl::<$line>(PhantomData))
}
fn create_business_order_processor(&self) -> Box<dyn BusinessOrderProcessor> {
Box::new(BusinessOrderProcessorImpl::<$line>(PhantomData))
}
fn create_hr_administrator(&self) -> Box<dyn HrAdministrator> {
Box::new(HrAdministratorImpl::<$line>(PhantomData))
}
fn create_it_operator(&self) -> Box<dyn ItOperator> {
Box::new(ItOperatorImpl::<$line>(PhantomData))
}
fn create_training_provider(&self) -> Box<dyn TrainingProvider> {
Box::new(TrainingProviderImpl::<$line>(PhantomData))
}
fn clone_factory(&self) -> Box<dyn ProductLineFactory> {
Box::new(Self)
}
}
};
}
impl_product_line_factory!(GoldProductLineFactory, GoldLine);
impl_product_line_factory!(DiamondProductLineFactory, DiamondLine);
impl_product_line_factory!(ColoredGemstoneProductLineFactory, ColoredGemstoneLine);
impl_product_line_factory!(PlatinumProductLineFactory, PlatinumLine);
// ==================== 单元测试 ====================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gold_factory_creation() {
let factory = GoldProductLineFactory;
let manufacturer = factory.create_manufacturer();
let steps = manufacturer.get_process_steps();
assert_eq!(steps.len(), 5);
assert_eq!(steps[0], "熔金");
}
#[test]
fn test_diamond_factory_creation() {
let factory = DiamondProductLineFactory;
let manufacturer = factory.create_manufacturer();
let steps = manufacturer.get_process_steps();
assert_eq!(steps.len(), 5);
assert_eq!(steps[0], "原石分拣");
}
#[test]
fn test_colored_gemstone_factory_creation() {
let factory = ColoredGemstoneProductLineFactory;
let manufacturer = factory.create_manufacturer();
let steps = manufacturer.get_process_steps();
assert_eq!(steps.len(), 5);
assert_eq!(steps[0], "宝石分拣");
}
#[test]
fn test_platinum_factory_creation() {
let factory = PlatinumProductLineFactory;
let manufacturer = factory.create_manufacturer();
let steps = manufacturer.get_process_steps();
assert_eq!(steps.len(), 6);
assert_eq!(steps[0], "铂金熔炼");
}
#[test]
fn test_material_verification() {
let factory = GoldProductLineFactory;
let verifier = factory.create_material_verifier();
let gold_batch = MaterialBatch {
batch_no: "BATCH-001".to_string(),
material_type: MaterialType::Gold,
purity_grade: 99.9,
weight_grams: 100.0,
supplier_id: "SUP-001".to_string(),
inbound_time: Utc::now(),
verify_status: VerifyStatus::Pending,
};
assert!(verifier.verify_batch(&gold_batch).is_ok());
}
#[test]
fn test_invoice_generation() {
let factory = GoldProductLineFactory;
let finance = factory.create_finance_processor();
let order = CustomerOrder {
order_id: "TEST-001".to_string(),
customer_id: "CUST-001".to_string(),
amount: 10000.0,
status: OrderStatus::Created,
created_at: Utc::now(),
};
let invoice = finance.generate_invoice(&order, 0.13).unwrap();
assert!(!invoice.invoice_no.is_empty());
assert_eq!(invoice.amount, 10000.0);
assert_eq!(invoice.tax_rate, 0.13);
}
}
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:43
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : models.rs
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
/// 原料批次信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialBatch {
/// 批次唯一编号
pub batch_no: String,
/// 原料类型(黄金/钻石/彩宝/铂金)
pub material_type: MaterialType,
/// 纯度/等级
pub purity_grade: f64,
/// 重量(克)
pub weight_grams: f64,
/// 供应商编号
pub supplier_id: String,
/// 入库时间
pub inbound_time: DateTime<Utc>,
/// 核验状态
pub verify_status: VerifyStatus,
}
/// 原料类型枚举
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MaterialType {
/// 足金/K金
Gold,
/// 钻石
Diamond,
/// 彩色宝石(红蓝绿宝等)
ColoredGemstone,
/// 铂金
Platinum,
}
/// 核验状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VerifyStatus {
/// 待核验
Pending,
/// 核验通过
Passed,
/// 核验失败
Failed,
}
/// 设计图纸规格
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesignSpec {
/// SKU编号
pub sku: String,
/// 3D模型文件路径
pub cad_file_url: String,
/// 设计师ID
pub designer_id: String,
/// 审批状态
pub approval_status: bool,
}
/// 生产工单
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkOrder {
/// 工单编号
pub work_order_no: String,
/// 关联SKU
pub sku: String,
/// 计划开始时间
pub planned_start: DateTime<Utc>,
/// 实际开始时间
pub actual_start: Option<DateTime<Utc>>,
/// 生产状态
pub status: ProductionStatus,
}
/// 生产状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProductionStatus {
/// 待排产
Pending,
/// 生产中
InProgress,
/// 已完成
Completed,
/// 已暂停
Paused,
}
/// 质检报告
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityReport {
/// 报告ID
pub report_id: String,
/// 关联工单
pub work_order_no: String,
/// 质检员ID
pub inspector_id: String,
/// 是否通过
pub passed: bool,
/// 质检标准
pub standard: String,
/// 报告生成时间
pub report_time: DateTime<Utc>,
}
/// 客户订单
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomerOrder {
/// 订单ID
pub order_id: String,
/// 客户ID
pub customer_id: String,
/// 订单金额(元)
pub amount: f64,
/// 订单状态
pub status: OrderStatus,
/// 创建时间
pub created_at: DateTime<Utc>,
}
/// 订单状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OrderStatus {
/// 已创建
Created,
/// 已支付
Paid,
/// 生产中
Producing,
/// 已发货
Shipped,
/// 已完成
Completed,
/// 已取消
Cancelled,
}
/// 物流运单
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryOrder {
/// 运单号
pub tracking_no: String,
/// 关联订单ID
pub order_id: String,
/// 承运商
pub carrier: String,
/// 保价金额
pub insured_value: f64,
/// 发货时间
pub shipped_at: DateTime<Utc>,
}
/// 财务发票
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Invoice {
/// 发票编号
pub invoice_no: String,
/// 关联订单ID
pub order_id: String,
/// 发票金额
pub amount: f64,
/// 税率
pub tax_rate: f64,
/// 开票时间
pub issued_at: DateTime<Utc>,
}
/// 营销活动主题
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketingCampaign {
/// 活动ID
pub campaign_id: String,
/// 活动主题
pub theme: String,
/// 开始时间
pub start_date: DateTime<Utc>,
/// 结束时间
pub end_date: DateTime<Utc>,
}
/// 员工排班
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmployeeShift {
/// 排班ID
pub shift_id: String,
/// 部门
pub department: String,
/// 员工ID
pub employee_id: String,
/// 班次类型
pub shift_type: ShiftType,
}
/// 班次类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ShiftType {
/// 早班
Morning,
/// 中班
Afternoon,
/// 晚班
Evening,
}
/// IT系统检查报告
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemCheckReport {
/// 检查ID
pub check_id: String,
/// 系统名称
pub system_name: String,
/// 检查状态
pub status: SystemStatus,
/// 检查时间
pub check_time: DateTime<Utc>,
}
/// 系统状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SystemStatus {
/// 正常
Healthy,
/// 警告
Warning,
/// 故障
Error,
}
/// 培训课件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingCourse {
/// 课程ID
pub course_id: String,
/// 课程名称
pub course_name: String,
/// 适用岗位
pub target_role: String,
/// 课件URL
pub material_url: String,
}
/// 生成唯一ID的工具函数
pub fn generate_id(prefix: &str) -> String {
let uuid = Uuid::new_v4();
format!("{}-{}", prefix, uuid.to_string()[..8].to_uppercase())
}
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:44
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : traits.rs
use crate::domain::errors::JewelryResult;
use crate::domain::models::*;
// ============================================================================
// 1. 原料采购核验模块
// ============================================================================
/// 原料采购核验Trait
/// 负责原料入库前的质量核验、成分检测、供应商资质审查
pub trait MaterialVerifier: Send + Sync {
/// 核验原料批次
/// # 参数
/// * `batch` - 待核验的原料批次信息
/// # 返回
/// 核验结果,包含核验报告或错误信息
fn verify_batch(&self, batch: &MaterialBatch) -> JewelryResult<String>;
/// 获取该核验器支持的原料类型
fn supported_material_type(&self) -> MaterialType;
/// 获取核验标准编号
fn verification_standard(&self) -> &str;
}
// ============================================================================
// 2. 设计制图模块
// ============================================================================
/// 设计制图Trait
/// 负责珠宝3D建模、CAD制图、设计审批
pub trait DesignDraftsman: Send + Sync {
/// 生成3D设计图
/// # 参数
/// * `spec` - 设计规格要求
/// # 返回
/// 3D模型文件路径
fn render_3d_model(&self, spec: &DesignSpec) -> JewelryResult<String>;
/// 检查CAD图纸是否符合生产标准
/// # 参数
/// * `cad_file_url` - CAD文件路径
/// # 返回
/// 是否符合标准
fn check_cad_standard(&self, cad_file_url: &str) -> JewelryResult<bool>;
/// 获取设计工具名称
fn design_tool_name(&self) -> &str;
}
// ============================================================================
// 3. 加工生产模块
// ============================================================================
/// 加工生产Trait
/// 负责珠宝的实际生产制造流程
pub trait Manufacturer: Send + Sync {
/// 开始生产工单
/// # 参数
/// * `work_order` - 生产工单
/// # 返回
/// 生产执行结果
fn start_production(&self, work_order: &WorkOrder) -> JewelryResult<String>;
/// 获取该制造商的工艺流程步骤
/// # 返回
/// 工艺流程步骤列表
fn get_process_steps(&self) -> Vec<String>;
/// 获取生产线名称
fn production_line_name(&self) -> &str;
}
// ============================================================================
// 4. 质检模块
// ============================================================================
/// 质检Trait
/// 负责成品的质量检验
pub trait QualityInspector: Send + Sync {
/// 执行质检
/// # 参数
/// * `work_order_no` - 工单编号
/// * `inspector_id` - 质检员ID
/// # 返回
/// 质检报告
fn inspect_product(&self, work_order_no: &str, inspector_id: &str) -> JewelryResult<QualityReport>;
/// 获取质检标准
fn quality_standard(&self) -> &str;
/// 获取质检设备名称
fn inspection_equipment(&self) -> &str;
}
// ============================================================================
// 5. 包装模块
// ============================================================================
/// 包装Trait
/// 负责珠宝成品的包装处理
pub trait Packager: Send + Sync {
/// 执行包装
/// # 参数
/// * `sku` - 商品SKU
/// * `order_id` - 关联订单ID
/// # 返回
/// 包装完成信息
fn pack_product(&self, sku: &str, order_id: &str) -> JewelryResult<String>;
/// 获取包装规格
fn packaging_specification(&self) -> &str;
}
// ============================================================================
// 6. 物流模块
// ============================================================================
/// 物流Trait
/// 负责珠宝的物流配送
pub trait LogisticsProvider: Send + Sync {
/// 创建物流运单
/// # 参数
/// * `order` - 客户订单
/// * `insured_value` - 保价金额
/// # 返回
/// 物流运单信息
fn create_delivery(&self, order: &CustomerOrder, insured_value: f64) -> JewelryResult<DeliveryOrder>;
/// 获取承运商名称
fn carrier_name(&self) -> &str;
}
// ============================================================================
// 7. 财务模块
// ============================================================================
/// 财务Trait
/// 负责发票生成、结算处理
pub trait FinanceProcessor: Send + Sync {
/// 生成发票
/// # 参数
/// * `order` - 客户订单
/// * `tax_rate` - 税率
/// # 返回
/// 发票信息
fn generate_invoice(&self, order: &CustomerOrder, tax_rate: f64) -> JewelryResult<Invoice>;
/// 获取财务系统名称
fn finance_system_name(&self) -> &str;
}
// ============================================================================
// 8. 营销推广模块
// ============================================================================
/// 营销推广Trait
/// 负责营销活动、推广物料生成
pub trait MarketingPromoter: Send + Sync {
/// 创建营销推广物料
/// # 参数
/// * `campaign` - 营销活动
/// * `sku` - 推广商品SKU
/// # 返回
/// 推广物料信息
fn create_promotion_material(&self, campaign: &MarketingCampaign, sku: &str) -> JewelryResult<String>;
/// 获取营销渠道
fn marketing_channel(&self) -> &str;
}
// ============================================================================
// 9. 业务订单模块
// ============================================================================
/// 业务订单Trait
/// 负责客户订单的创建与管理
pub trait BusinessOrderProcessor: Send + Sync {
/// 创建客户订单
/// # 参数
/// * `customer_id` - 客户ID
/// * `sku` - 商品SKU
/// * `amount` - 订单金额
/// # 返回
/// 客户订单信息
fn create_order(&self, customer_id: &str, sku: &str, amount: f64) -> JewelryResult<CustomerOrder>;
/// 获取业务系统名称
fn business_system_name(&self) -> &str;
}
// ============================================================================
// 10. 人事行政模块
// ============================================================================
/// 人事行政Trait
/// 负责员工排班、行政管理
pub trait HrAdministrator: Send + Sync {
/// 安排员工排班
/// # 参数
/// * `department` - 部门名称
/// * `employee_id` - 员工ID
/// # 返回
/// 排班信息
fn arrange_shift(&self, department: &str, employee_id: &str) -> JewelryResult<EmployeeShift>;
/// 获取人力资源系统名称
fn hr_system_name(&self) -> &str;
}
// ============================================================================
// 11. IT运维模块
// ============================================================================
/// IT运维Trait
/// 负责系统健康检查、运维监控
pub trait ItOperator: Send + Sync {
/// 执行系统健康检查
/// # 返回
/// 系统检查报告
fn system_health_check(&self) -> JewelryResult<SystemCheckReport>;
/// 获取运维平台名称
fn ops_platform_name(&self) -> &str;
}
// ============================================================================
// 12. 培训模块
// ============================================================================
/// 培训Trait
/// 负责员工培训、课件管理
pub trait TrainingProvider: Send + Sync {
/// 获取培训课程
/// # 参数
/// * `role` - 目标岗位
/// # 返回
/// 培训课程信息
fn get_training_course(&self, role: &str) -> JewelryResult<TrainingCourse>;
/// 获取培训平台名称
fn training_platform_name(&self) -> &str;
}
rust
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Factory Method Pattern 工厂方法模式 创建型模式 Creational Patterns
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:36
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : logging.rs
use chrono::Local;
use std::fs::OpenOptions;
use std::io::Write;
pub struct Logger;
impl Logger {
pub fn log(level: &str, module: &str, message: &str) {
let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
let log_line = format!("[{}] [{}] [{}] {}\n", timestamp, level, module, message);
// 输出到控制台
print!("{}", log_line);
// 同时写入日志文件(可选)
if let Ok(mut file) = OpenOptions::new()
.create(true)
.append(true)
.open("app.log")
{
let _ = file.write_all(log_line.as_bytes());
}
}
pub fn info(module: &str, message: &str) {
Self::log("INFO", module, message);
}
pub fn warn(module: &str, message: &str) {
Self::log("WARN", module, message);
}
pub fn error(module: &str, message: &str) {
Self::log("ERROR", module, message);
}
pub fn debug(module: &str, message: &str) {
Self::log("DEBUG", module, message);
}
}
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Factory Method Pattern 工厂方法模式 创建型模式 Creational Patterns
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:39
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : message_queue.rs
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
pub struct MessageQueue<T> {
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> MessageQueue<T> {
pub fn new() -> Self {
MessageQueue {
queue: Arc::new(Mutex::new(VecDeque::new())),
}
}
pub fn push(&self, item: T) {
let mut queue = self.queue.lock().unwrap();
queue.push_back(item);
}
pub fn pop(&self) -> Option<T> {
let mut queue = self.queue.lock().unwrap();
queue.pop_front()
}
pub fn len(&self) -> usize {
let queue = self.queue.lock().unwrap();
queue.len()
}
pub fn is_empty(&self) -> bool {
let queue = self.queue.lock().unwrap();
queue.is_empty()
}
}
impl<T> Clone for MessageQueue<T> {
fn clone(&self) -> Self {
MessageQueue {
queue: Arc::clone(&self.queue),
}
}
}
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Factory Method Pattern 工厂方法模式 创建型模式 Creational Patterns
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:37
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : thread_pool.rs
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Option<mpsc::Sender<Job>>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl ThreadPool {
/// 创建新的线程池,指定线程数量
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0, "线程池大小必须大于0");
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool {
workers,
sender: Some(sender),
}
}
/// 向线程池提交任务
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
if let Some(ref sender) = self.sender {
sender.send(job).expect("无法发送任务到线程池");
}
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
// 关闭发送端,让所有工作线程退出
drop(self.sender.take());
for worker in &mut self.workers {
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || {
loop {
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) => {
job();
}
Err(_) => {
break;
}
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}
rust
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Factory Method Pattern 工厂方法模式 创建型模式 Creational Patterns
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:40
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : retry.rs
use std::thread;
use std::time::Duration;
/// 重试配置
pub struct RetryConfig {
pub max_retries: u32,
pub delay_ms: u64,
pub backoff_multiplier: f64,
}
impl Default for RetryConfig {
fn default() -> Self {
RetryConfig {
max_retries: 3,
delay_ms: 1000,
backoff_multiplier: 2.0,
}
}
}
/// 带重试机制的执行函数
pub fn execute_with_retry<F, T, E>(
mut operation: F,
config: &RetryConfig,
) -> Result<T, E>
where
F: FnMut() -> Result<T, E>,
E: std::fmt::Debug,
{
let mut last_error = None;
let mut delay = config.delay_ms;
for attempt in 0..=config.max_retries {
match operation() {
Ok(result) => return Ok(result),
Err(e) => {
last_error = Some(e);
if attempt < config.max_retries {
thread::sleep(Duration::from_millis(delay));
delay = (delay as f64 * config.backoff_multiplier) as u64;
}
}
}
}
Err(last_error.unwrap())
}
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:Factory Method Pattern 工厂方法模式 创建型模式 Creational Patterns
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:40
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : services.rs
use crate::domain::models::*;
use crate::domain::factory::*;
use crate::infrastructure::logging::Logger;
use crate::infrastructure::thread_pool::ThreadPool;
use crate::infrastructure::message_queue::MessageQueue;
use crate::application::retry::{execute_with_retry, RetryConfig};
pub struct OrderProcessingService {
thread_pool: ThreadPool,
order_queue: MessageQueue<CustomerOrder>,
}
impl OrderProcessingService {
pub fn new(pool_size: usize) -> Self {
OrderProcessingService {
thread_pool: ThreadPool::new(pool_size),
order_queue: MessageQueue::new(),
}
}
/// 处理订单
pub fn process_order(&self, order: CustomerOrder, factory: &dyn ProductLineFactory) {
Logger::info("OrderProcessingService", &format!("开始处理订单: {}", order.order_id));
let order_clone = order.clone();
let factory_ref = factory.clone_factory();
self.thread_pool.execute(move || {
// 1. 创建制造任务
let manufacturer = factory_ref.create_manufacturer();
let steps = manufacturer.get_process_steps();
Logger::info("OrderProcessingService", &format!("制造流程: {:?}", steps));
// 2. 质量检验
let inspector = factory_ref.create_quality_inspector();
match inspector.inspect_product(&order_clone.order_id, &format!("INS-{}", order_clone.order_id)) {
Ok(report) => {
Logger::info("OrderProcessingService", &format!("质检报告: 通过={}, 标准={}", report.passed, report.standard));
}
Err(e) => {
Logger::error("OrderProcessingService", &format!("质检失败: {:?}", e));
return;
}
}
// 3. 财务处理
let finance = factory_ref.create_finance_processor();
match finance.generate_invoice(&order_clone, 0.13) {
Ok(invoice) => {
let tax_amount = invoice.amount * invoice.tax_rate;
Logger::info("OrderProcessingService", &format!("发票生成: 金额={}, 税额={}", invoice.amount, tax_amount));
}
Err(e) => {
Logger::error("OrderProcessingService", &format!("财务处理失败: {:?}", e));
return;
}
}
// 4. 物流安排
let logistics = factory_ref.create_logistics_provider();
match logistics.create_delivery(&order_clone, order_clone.amount) {
Ok(delivery) => {
Logger::info("OrderProcessingService", &format!("物流安排: 承运商={}, 保价={}", delivery.carrier, delivery.insured_value));
}
Err(e) => {
Logger::error("OrderProcessingService", &format!("物流安排失败: {:?}", e));
}
}
Logger::info("OrderProcessingService", &format!("订单处理完成: {}", order_clone.order_id));
});
}
/// 批量处理订单(带重试机制)
pub fn batch_process_orders(&self, orders: Vec<CustomerOrder>, factory: &dyn ProductLineFactory) {
for order in orders {
let config = RetryConfig::default();
let order_clone = order.clone();
let factory_ref = factory.clone_factory();
let result = execute_with_retry(
|| {
// 模拟可能失败的操作
self.process_order(order_clone.clone(), &*factory_ref);
Ok::<(), String>(())
},
&config,
);
match result {
Ok(_) => Logger::info("OrderProcessingService", &format!("订单 {} 处理成功", order.order_id)),
Err(e) => Logger::error("OrderProcessingService", &format!("订单 {} 处理失败: {}", order.order_id, e)),
}
}
}
}
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述:
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:48
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : cli.rs
use crate::domain::models::*;
use crate::domain::factory::*;
use crate::application::services::OrderProcessingService;
use crate::infrastructure::logging::Logger;
use chrono::Utc;
pub struct CommandLineInterface;
impl CommandLineInterface {
pub fn run() {
Logger::info("CLI", "珠宝制造业务系统启动");
// 创建服务
let service = OrderProcessingService::new(4);
// 演示黄金产品线
Logger::info("CLI", "=== 黄金产品线演示 ===");
let gold_factory = GoldProductLineFactory;
let gold_order = CustomerOrder {
order_id: "GO-2024-001".to_string(),
customer_id: "CUST-001".to_string(),
amount: 50000.0,
status: OrderStatus::Created,
created_at: Utc::now(),
};
service.process_order(gold_order, &gold_factory);
// 演示钻石产品线
Logger::info("CLI", "=== 钻石产品线演示 ===");
let diamond_factory = DiamondProductLineFactory;
let diamond_order = CustomerOrder {
order_id: "DO-2024-001".to_string(),
customer_id: "CUST-002".to_string(),
amount: 100000.0,
status: OrderStatus::Created,
created_at: Utc::now(),
};
service.process_order(diamond_order, &diamond_factory);
// 演示彩色宝石产品线
Logger::info("CLI", "=== 彩色宝石产品线演示 ===");
let gemstone_factory = ColoredGemstoneProductLineFactory;
let gemstone_order = CustomerOrder {
order_id: "CGO-2024-001".to_string(),
customer_id: "CUST-003".to_string(),
amount: 30000.0,
status: OrderStatus::Created,
created_at: Utc::now(),
};
service.process_order(gemstone_order, &gemstone_factory);
// 演示铂金产品线
Logger::info("CLI", "=== 铂金产品线演示 ===");
let platinum_factory = PlatinumProductLineFactory;
let platinum_order = CustomerOrder {
order_id: "PO-2024-001".to_string(),
customer_id: "CUST-004".to_string(),
amount: 80000.0,
status: OrderStatus::Created,
created_at: Utc::now(),
};
service.process_order(platinum_order, &platinum_factory);
// 等待线程池完成任务
Logger::info("CLI", "等待所有任务完成...");
std::thread::sleep(std::time::Duration::from_secs(2));
Logger::info("CLI", "珠宝制造业务系统关闭");
}
}
调用:
rust
//!# encoding: utf-8
//!# 版权所有 2026 ©涂聚文有限公司™ ®
//!# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
//!# 描述: Factory Method Pattern 工厂方法模式 创建型模式 Creational Patterns
//!# Author : geovindu,Geovin Du 涂聚文.
//!# IDE : RustRover 2025.1.1 Rust
//!# os : windows 10
//!# database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//!# Datetime : 2026/9/17 22:36
//!# User : geovindu
//!# Product : RustRover
//!# Project : FactoryMethodPattern
//!# File : main.rs
#![allow(dead_code)]
mod domain;
mod infrastructure;
mod application;
mod presentation;
fn main() {
presentation::cli::CommandLineInterface::run();
}
输出:
