rust
//! # encoding: utf-8
//! # 版权所有 2026 ©涂聚文有限公司™ ®
//! # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 在企业级高并发系统中,引入"重试机制"和"死信队列(Dead Letter Queue)"是保障系统高可用性的关键防线。
//! # 描述:desgin pattern Typestate pattern
//! # Author : geovindu,Geovin Du 涂聚文.
//! # IDE : RustRover 2025.1.1
//! # os : windows 10
//! # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//! # Datetime : 2026/9/12 12:51
//! # User : geovindu
//! # Product : RustRover
//! # Project : desginpattern
//! # File : main.rs
use std::marker::PhantomData;
// ================= 1. 基础业务模块定义 =================
#[derive(Debug, Clone, Default)] pub struct RawMaterial { pub cert_no: String, pub purity: f32 }
#[derive(Debug, Clone, Default)] pub struct DesignSpec { pub cad_file_url: String }
#[derive(Debug, Clone, Default)] pub struct Production { pub workshop_id: u64 }
#[derive(Debug, Clone, Default)] pub struct QualityControl { pub passed: bool, pub report_url: String }
#[derive(Debug, Clone, Default)] pub struct Packaging { pub anti_tamper_seal: bool }
#[derive(Debug, Clone, Default)] pub struct Logistics { pub insured_value: f32, pub tracking_no: String }
#[derive(Debug, Clone, Default)] pub struct Finance { pub invoice_issued: bool }
// 支撑部门模块
#[derive(Debug, Clone, Default)] pub struct Marketing { pub campaign_id: Option<String> }
#[derive(Debug, Clone, Default)] pub struct HrAdmin { pub new_staff_onboarded: bool, pub security_cleared: bool }
#[derive(Debug, Clone, Default)] pub struct ItSupport { pub erp_synced: bool, pub crm_updated: bool }
#[derive(Debug, Clone, Default)] pub struct Training { pub new_craft_trained: bool, pub compliance_done: bool }
// ================= 2. 状态机定义 =================
pub struct Draft; // 初始:原料、设计、加工
pub struct QcPending; // 待质检
pub struct ReadyToShip; // 就绪:质检通过,可包装、物流、财务
pub struct Finalizing; // 最终配置:收集营销、人事、IT、培训等旁路数据
// ================= 3. 泛型 Builder =================
pub struct JewelryOrderBuilder<State> {
order_id: String,
// 核心业务数据
material: Option<RawMaterial>,
design: Option<DesignSpec>,
production: Option<Production>,
qc: Option<QualityControl>,
packaging: Option<Packaging>,
logistics: Option<Logistics>,
finance: Option<Finance>,
// 支撑部门数据
marketing: Option<Marketing>,
hr_admin: Option<HrAdmin>,
it_support: Option<ItSupport>,
training: Option<Training>,
_state: PhantomData<State>,
}
// ================= 4. 状态流转与业务方法 =================
/// 阶段一:草稿状态 (Draft)
impl JewelryOrderBuilder<Draft> {
pub fn new(order_id: &str) -> Self {
Self {
order_id: order_id.to_string(),
material: None, design: None, production: None, qc: None,
packaging: None, logistics: None, finance: None,
marketing: None, hr_admin: None, it_support: None, training: None,
_state: PhantomData,
}
}
pub fn with_material(mut self, m: RawMaterial) -> Self { self.material = Some(m); self }
pub fn with_design(mut self, d: DesignSpec) -> Self { self.design = Some(d); self }
pub fn with_production(mut self, p: Production) -> Self { self.production = Some(p); self }
pub fn submit_for_qc(self) -> Result<JewelryOrderBuilder<QcPending>, String> {
if self.material.is_none() || self.design.is_none() || self.production.is_none() {
return Err("Cannot submit to QC: Missing core prerequisites.".into());
}
Ok(JewelryOrderBuilder { order_id: self.order_id, material: self.material, design: self.design, production: self.production, qc: None, packaging: None, logistics: None, finance: None, marketing: None, hr_admin: None, it_support: None, training: None, _state: PhantomData })
}
}
/// 阶段二:待质检状态 (QcPending)
impl JewelryOrderBuilder<QcPending> {
pub fn record_qc_result(mut self, qc: QualityControl) -> Result<JewelryOrderBuilder<ReadyToShip>, String> {
if !qc.passed { return Err(format!("Order {} FAILED QC.", self.order_id)); }
self.qc = Some(qc);
Ok(JewelryOrderBuilder { order_id: self.order_id, material: self.material, design: self.design, production: self.production, qc: self.qc, packaging: None, logistics: None, finance: None, marketing: None, hr_admin: None, it_support: None, training: None, _state: PhantomData })
}
}
/// 阶段三:就绪状态 (ReadyToShip)
impl JewelryOrderBuilder<ReadyToShip> {
pub fn with_packaging(mut self, p: Packaging) -> Self { self.packaging = Some(p); self }
pub fn with_logistics(mut self, l: Logistics) -> Self { self.logistics = Some(l); self }
pub fn with_finance(mut self, f: Finance) -> Self { self.finance = Some(f); self }
/// 进入最终配置阶段(开始收集支撑部门数据)
pub fn begin_finalizing(self) -> JewelryOrderBuilder<Finalizing> {
JewelryOrderBuilder {
order_id: self.order_id, material: self.material, design: self.design, production: self.production, qc: self.qc, packaging: self.packaging, logistics: self.logistics, finance: self.finance,
marketing: None, hr_admin: None, it_support: None, training: None,
_state: PhantomData,
}
}
}
/// 阶段四:最终配置状态 (Finalizing) - 专门处理支撑部门
impl JewelryOrderBuilder<Finalizing> {
pub fn with_marketing(mut self, m: Marketing) -> Self { self.marketing = Some(m); self }
pub fn with_hr_admin(mut self, h: HrAdmin) -> Self { self.hr_admin = Some(h); self }
pub fn with_it_support(mut self, i: ItSupport) -> Self { self.it_support = Some(i); self }
pub fn with_training(mut self, t: Training) -> Self { self.training = Some(t); self }
/// 最终构建
pub fn build(self) -> Result<JewelryOrderPipeline, String> {
Ok(JewelryOrderPipeline {
order_id: self.order_id,
material: self.material.unwrap(), design: self.design.unwrap(), production: self.production.unwrap(), qc: self.qc.unwrap(), packaging: self.packaging.unwrap(), logistics: self.logistics.unwrap(), finance: self.finance.unwrap(),
marketing: self.marketing, hr_admin: self.hr_admin, it_support: self.it_support, training: self.training,
})
}
}
// ================= 5. 最终产出的不可变订单对象 =================
#[derive(Debug)]
pub struct JewelryOrderPipeline {
pub order_id: String,
// 核心业务
pub material: RawMaterial, pub design: DesignSpec, pub production: Production, pub qc: QualityControl, pub packaging: Packaging, pub logistics: Logistics, pub finance: Finance,
// 支撑部门 (Option 表示可选)
pub marketing: Option<Marketing>, pub hr_admin: Option<HrAdmin>, pub it_support: Option<ItSupport>, pub training: Option<Training>,
}
// ================= 6. 业务演示 =================
fn main() {
let result = JewelryOrderBuilder::new("ORD-2024-8888")
.with_material(RawMaterial { cert_no: "GIA-999".into(), purity: 0.999 })
.with_design(DesignSpec { cad_file_url: "s3://cad.step".into() })
.with_production(Production { workshop_id: 3 })
.submit_for_qc().unwrap()
.record_qc_result(QualityControl { passed: true, report_url: "s3://qc/pass.pdf".into() }).unwrap()
.with_packaging(Packaging { anti_tamper_seal: true })
.with_logistics(Logistics { insured_value: 100000.0, tracking_no: "BRK-888".into() })
.with_finance(Finance { invoice_issued: true })
// 进入支撑部门配置阶段
.begin_finalizing()
.with_marketing(Marketing { campaign_id: Some("VIP-2024".into()) })
.with_hr_admin(HrAdmin { new_staff_onboarded: true, security_cleared: true })
.with_it_support(ItSupport { erp_synced: true, crm_updated: true })
.with_training(Training { new_craft_trained: true, compliance_done: true })
.build();
match result {
Ok(order) => println!("✅ 珠宝订单全链路构建成功:\n{:#?}", order),
Err(e) => println!("❌ 业务阻断: {}", e),
}
}
rust
//! # encoding: utf-8
//! # 版权所有 2026 ©涂聚文有限公司™ ®
//! # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎 在企业级高并发系统中,引入"重试机制"和"死信队列(Dead Letter Queue)"是保障系统高可用性的关键防线。
//! # 描述:desgin pattern Builder pattern
//! # Author : geovindu,Geovin Du 涂聚文.
//! # IDE : RustRover 2025.1.1
//! # os : windows 10
//! # database : mysql 9.0 sql server 2019, postgreSQL 17.0 Oracle 21c Neo4j
//! # Datetime : 2026/9/12 12:51
//! # User : geovindu
//! # Product : RustRover
//! # Project : desginpattern
//! # File : main.rs
//!
//!
//! use std::fmt;
// ================= 1. 基础模块定义 =================
#[derive(Debug, Clone)]
pub struct RawMaterial {
pub sku: String,
pub purity: f32, // 纯度,如 0.750 (18K) 或 0.999 (足金)
pub weight_g: f32,
pub cert_no: String, // 原料核验证书号
}
#[derive(Debug, Clone)]
pub struct DesignSpec {
pub cad_file_url: String,
pub designer_id: u64,
pub approval_status: bool,
}
#[derive(Debug, Clone)]
pub struct Production {
pub workshop_id: u64,
pub start_time: String,
pub end_time: String,
}
#[derive(Debug, Clone)]
pub struct QualityControl {
pub passed: bool,
pub inspector_id: u64,
pub report_url: String,
}
#[derive(Debug, Clone)]
pub struct Packaging {
pub box_type: String,
pub ribbon_color: String,
pub anti_tamper_seal: bool,
}
#[derive(Debug, Clone)]
pub struct Logistics {
pub carrier: String,
pub insured_value: f32, // 珠宝必须保价
pub tracking_no: Option<String>,
}
#[derive(Debug, Clone)]
pub struct Finance {
pub payment_method: String,
pub invoice_issued: bool,
pub tax_rate: f32,
}
#[derive(Debug, Clone)]
pub struct Marketing {
pub campaign_id: Option<String>,
pub promo_code: Option<String>,
}
// 支撑部门配置
#[derive(Debug, Clone, Default)]
pub struct SupportDepartments {
pub hr_onboarding: bool,
pub admin_logistics: bool,
pub it_system_sync: bool,
pub training_required: bool,
}
// ================= 2. 核心流水线结构体 =================
#[derive(Debug)]
pub struct JewelryOrderPipeline {
pub order_id: String,
pub customer_id: u64,
pub material: RawMaterial,
pub design: DesignSpec,
pub production: Production,
pub qc: QualityControl,
pub packaging: Packaging,
pub logistics: Logistics,
pub finance: Finance,
pub marketing: Option<Marketing>,
pub support: SupportDepartments,
}
// ================= 3. Builder 实现 =================
pub struct PipelineBuilder {
order_id: Option<String>,
customer_id: Option<u64>,
material: Option<RawMaterial>,
design: Option<DesignSpec>,
production: Option<Production>,
qc: Option<QualityControl>,
packaging: Option<Packaging>,
logistics: Option<Logistics>,
finance: Option<Finance>,
marketing: Option<Marketing>,
support: SupportDepartments,
}
impl PipelineBuilder {
pub fn new(order_id: &str, customer_id: u64) -> Self {
Self {
order_id: Some(order_id.to_string()),
customer_id: Some(customer_id),
material: None, design: None, production: None, qc: None,
packaging: None, logistics: None, finance: None, marketing: None,
support: SupportDepartments::default(),
}
}
// 核心业务链
pub fn with_material(mut self, m: RawMaterial) -> Self { self.material = Some(m); self }
pub fn with_design(mut self, d: DesignSpec) -> Self { self.design = Some(d); self }
pub fn with_production(mut self, p: Production) -> Self { self.production = Some(p); self }
pub fn with_qc(mut self, q: QualityControl) -> Self { self.qc = Some(q); self }
pub fn with_packaging(mut self, p: Packaging) -> Self { self.packaging = Some(p); self }
pub fn with_logistics(mut self, l: Logistics) -> Self { self.logistics = Some(l); self }
pub fn with_finance(mut self, f: Finance) -> Self { self.finance = Some(f); self }
// 营销推广
pub fn with_marketing(mut self, m: Marketing) -> Self { self.marketing = Some(m); self }
// 支撑部门配置
pub fn enable_hr(mut self) -> Self { self.support.hr_onboarding = true; self }
pub fn enable_admin(mut self) -> Self { self.support.admin_logistics = true; self }
pub fn enable_it_sync(mut self) -> Self { self.support.it_system_sync = true; self }
pub fn enable_training(mut self) -> Self { self.support.training_required = true; self }
/// 构建并执行企业级业务校验
pub fn build(self) -> Result<JewelryOrderPipeline, String> {
// 1. 基础字段完整性校验
let order_id = self.order_id.ok_or("Order ID is required")?;
let customer_id = self.customer_id.ok_or("Customer ID is required")?;
let material = self.material.ok_or("Raw material verification is missing")?;
let design = self.design.ok_or("Design spec is missing")?;
let production = self.production.ok_or("Production schedule is missing")?;
let qc = self.qc.ok_or("Quality control record is missing")?;
let packaging = self.packaging.ok_or("Packaging config is missing")?;
let logistics = self.logistics.ok_or("Logistics setup is missing")?;
let finance = self.finance.ok_or("Finance settlement is missing")?;
// 2. 珠宝行业核心业务规则校验 (已修复合规逻辑)
if !qc.passed {
return Err(format!("Order {} blocked: Failed QC inspection.", order_id));
}
// 修复点:珠宝行业允许 18K 金 (纯度 0.750),因此将阈值调整为 0.750
if material.purity < 0.750 {
return Err("Compliance Error: Gold purity below 750 (18K) is not allowed for fine jewelry.".to_string());
}
if logistics.insured_value <= 0.0 {
return Err("Security Error: High-value jewelry must have positive insured value.".to_string());
}
Ok(JewelryOrderPipeline {
order_id, customer_id, material, design, production, qc, packaging, logistics, finance,
marketing: self.marketing, support: self.support,
})
}
}
// ================= 4. 业务演示 =================
fn main() {
// 模拟一个 18K 钻戒定制订单 (纯度为 0.750)
let result = PipelineBuilder::new("ORD-2024-8899", 10086)
.with_material(RawMaterial {
sku: "AU750-DIA-01".into(),
purity: 0.750, // 18K 金
weight_g: 5.2,
cert_no: "GIA-22334455".into(),
})
.with_design(DesignSpec {
cad_file_url: "s3://cad/ORD-8899_v2.step".into(),
designer_id: 501, approval_status: true,
})
.with_production(Production {
workshop_id: 3,
start_time: "2024-05-01T09:00:00Z".into(),
end_time: "2024-05-05T18:00:00Z".into(),
})
.with_qc(QualityControl {
passed: true, inspector_id: 88, report_url: "s3://qc/ORD-8899_pass.pdf".into(),
})
.with_packaging(Packaging {
box_type: "Velvet-Luxury-Black".into(), ribbon_color: "Gold".into(), anti_tamper_seal: true,
})
.with_logistics(Logistics {
carrier: "Brinks-Armored".into(), insured_value: 50000.0, tracking_no: Some("BRK-99887766".into()),
})
.with_finance(Finance {
payment_method: "Wire-Transfer".into(), invoice_issued: true, tax_rate: 0.13,
})
.with_marketing(Marketing {
campaign_id: Some("VIP-Spring-2024".into()), promo_code: None,
})
.enable_it_sync()
.enable_training()
.build();
match result {
Ok(pipeline) => {
println!("✅ 珠宝订单全链路构建成功!");
println!("{:#?}", pipeline);
}
Err(e) => {
println!("❌ 业务流程阻断: {}", e);
}
}
}
输出:
