四种对象型创建模式:抽象工厂、 build模式、原型ProtoType与单例模式

1. 抽象工厂模式 (Abstract Factory)

组件框图

bash 复制代码
┌─────────────────┐         ┌──────────────────┐
│   Client        │         │ AbstractFactory  │
├─────────────────┤         ├──────────────────┤
│                 │───────>│+createProductA()  │
│                 │         │+createProductB()  │
└─────────────────┘         └──────────────────┘
                                      △
                     ┌─────────────────┼─────────────────┐
           ┌──────────┴──────────┐            ┌──────────┴──────────┐
           │ ConcreteFactory1    │            │ ConcreteFactory2    │
           ├─────────────────────┤            ├─────────────────────┤
           │+createProductA()    │            │+createProductA()    │
           │+createProductB()    │            │+createProductB()    │
           └─────────────────────┘            └─────────────────────┘
                     │                                  │
           ┌─────────┼─────────┐              ┌─────────┼─────────┐
    ┌──────┴─────┐ ┌─┴──────┐        ┌──────┴─────┐ ┌─┴──────┐
    │ ProductA1  │ │ProductB1│        │ ProductA2  │ │ProductB2│
    └────────────┘ └─────────┘        └────────────┘ └─────────┘

详细描述

问题:

需要创建一系列相关或依赖的对象,但不希望指定具体的类。例如,需要创建跨平台的UI组件。

解决方案:

提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

效果:

  • 优点:保证产品系列的兼容性,易于交换产品系列

  • 缺点:难以支持新种类的产品

Python实现

python 复制代码
from abc import ABC, abstractmethod

# 抽象产品A
class Button(ABC):
    @abstractmethod
    def render(self):
        pass

# 抽象产品B
class Checkbox(ABC):
    @abstractmethod
    def paint(self):
        pass

# 具体产品A1
class WindowsButton(Button):
    def render(self):
        return "渲染Windows风格按钮"

# 具体产品B1
class WindowsCheckbox(Checkbox):
    def paint(self):
        return "绘制Windows风格复选框"

# 具体产品A2
class MacButton(Button):
    def render(self):
        return "渲染macOS风格按钮"

# 具体产品B2
class MacCheckbox(Checkbox):
    def paint(self):
        return "绘制macOS风格复选框"

# 抽象工厂
class GUIFactory(ABC):
    @abstractmethod
    def create_button(self) -> Button:
        pass
    
    @abstractmethod
    def create_checkbox(self) -> Checkbox:
        pass

# 具体工厂1
class WindowsFactory(GUIFactory):
    def create_button(self) -> Button:
        return WindowsButton()
    
    def create_checkbox(self) -> Checkbox:
        return WindowsCheckbox()

# 具体工厂2
class MacFactory(GUIFactory):
    def create_button(self) -> Button:
        return MacButton()
    
    def create_checkbox(self) -> Checkbox:
        return MacCheckbox()

# 客户端代码
class Application:
    def __init__(self, factory: GUIFactory):
        self.factory = factory
        self.button = None
        self.checkbox = None
    
    def create_ui(self):
        self.button = self.factory.create_button()
        self.checkbox = self.factory.create_checkbox()
    
    def paint(self):
        print(self.button.render())
        print(self.checkbox.paint())

# 使用
if __name__ == "__main__":
    print("=== Windows UI ===")
    windows_factory = WindowsFactory()
    app1 = Application(windows_factory)
    app1.create_ui()
    app1.paint()
    
    print("\n=== macOS UI ===")
    mac_factory = MacFactory()
    app2 = Application(mac_factory)
    app2.create_ui()
    app2.paint()

C++实现

cpp 复制代码
#include <iostream>
#include <memory>
#include <string>

// 抽象产品A
class Button {
public:
    virtual ~Button() = default;
    virtual std::string render() = 0;
};

// 抽象产品B
class Checkbox {
public:
    virtual ~Checkbox() = default;
    virtual std::string paint() = 0;
};

// 具体产品A1
class WindowsButton : public Button {
public:
    std::string render() override {
        return "渲染Windows风格按钮";
    }
};

// 具体产品B1
class WindowsCheckbox : public Checkbox {
public:
    std::string paint() override {
        return "绘制Windows风格复选框";
    }
};

// 具体产品A2
class MacButton : public Button {
public:
    std::string render() override {
        return "渲染macOS风格按钮";
    }
};

// 具体产品B2
class MacCheckbox : public Checkbox {
public:
    std::string paint() override {
        return "绘制macOS风格复选框";
    }
};

// 抽象工厂
class GUIFactory {
public:
    virtual ~GUIFactory() = default;
    virtual std::unique_ptr<Button> createButton() = 0;
    virtual std::unique_ptr<Checkbox> createCheckbox() = 0;
};

// 具体工厂1
class WindowsFactory : public GUIFactory {
public:
    std::unique_ptr<Button> createButton() override {
        return std::make_unique<WindowsButton>();
    }
    
    std::unique_ptr<Checkbox> createCheckbox() override {
        return std::make_unique<WindowsCheckbox>();
    }
};

// 具体工厂2
class MacFactory : public GUIFactory {
public:
    std::unique_ptr<Button> createButton() override {
        return std::make_unique<MacButton>();
    }
    
    std::unique_ptr<Checkbox> createCheckbox() override {
        return std::make_unique<MacCheckbox>();
    }
};

// 客户端代码
class Application {
private:
    std::unique_ptr<GUIFactory> factory;
    std::unique_ptr<Button> button;
    std::unique_ptr<Checkbox> checkbox;
    
public:
    Application(std::unique_ptr<GUIFactory> factory) 
        : factory(std::move(factory)) {}
    
    void createUI() {
        button = this->factory->createButton();
        checkbox = this->factory->createCheckbox();
    }
    
    void paint() {
        std::cout << button->render() << std::endl;
        std::cout << checkbox->paint() << std::endl;
    }
};

// 使用
int main() {
    std::cout << "=== Windows UI ===" << std::endl;
    auto windowsFactory = std::make_unique<WindowsFactory>();
    Application app1(std::move(windowsFactory));
    app1.createUI();
    app1.paint();
    
    std::cout << "\n=== macOS UI ===" << std::endl;
    auto macFactory = std::make_unique<MacFactory>();
    Application app2(std::move(macFactory));
    app2.createUI();
    app2.paint();
    
    return 0;
}

2. 建造者模式 (Builder)

组件框图

bash 复制代码
┌─────────────────┐         ┌──────────────────┐
│   Director      │         │    Builder       │
├─────────────────┤         ├──────────────────┤
│+construct()     │───────>│+buildPartA()     │
│                 │         │+buildPartB()     │
│                 │         │+getResult()      │
└─────────────────┘         └──────────────────┘
                                      △
                     ┌─────────────────┼─────────────────┐
           ┌──────────┴──────────┐            ┌──────────┴──────────┐
           │ ConcreteBuilder1    │            │ ConcreteBuilder2    │
           ├─────────────────────┤            ├─────────────────────┤
           │+buildPartA()        │            │+buildPartA()        │
           │+buildPartB()        │            │+buildPartB()        │
           │+getResult()         │            │+getResult()         │
           └─────────────────────┘            └─────────────────────┘
                     │                                  │
           ┌─────────┴─────────┐              ┌─────────┴─────────┐
           │     Product1      │              │     Product2      │
           └───────────────────┘              └───────────────────┘

详细描述

问题:

创建复杂对象时,构造过程复杂且可能有多个步骤,或者需要创建不同表示的对象。

解决方案:

将复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

效果:

  • 优点:封装了复杂对象的创建过程,可以精细控制构建过程

  • 缺点:增加了系统复杂度,需要多个具体建造者类

Python实现

python 复制代码
from abc import ABC, abstractmethod
from typing import List

# 产品类
class Computer:
    def __init__(self):
        self.parts: List[str] = []
    
    def add(self, part: str):
        self.parts.append(part)
    
    def list_parts(self):
        return f"计算机配置: {', '.join(self.parts)}"
    
    def __str__(self):
        return self.list_parts()

# 抽象建造者
class ComputerBuilder(ABC):
    def __init__(self):
        self.computer = Computer()
    
    @abstractmethod
    def build_cpu(self):
        pass
    
    @abstractmethod
    def build_memory(self):
        pass
    
    @abstractmethod
    def build_storage(self):
        pass
    
    @abstractmethod
    def build_graphics_card(self):
        pass
    
    def get_computer(self) -> Computer:
        computer = self.computer
        self.computer = Computer()  # 重置用于下次构建
        return computer

# 具体建造者 - 游戏电脑
class GamingComputerBuilder(ComputerBuilder):
    def build_cpu(self):
        self.computer.add("Intel i9-13900K CPU")
    
    def build_memory(self):
        self.computer.add("32GB DDR5 RAM")
    
    def build_storage(self):
        self.computer.add("2TB NVMe SSD")
    
    def build_graphics_card(self):
        self.computer.add("NVIDIA RTX 4090")

# 具体建造者 - 办公电脑
class OfficeComputerBuilder(ComputerBuilder):
    def build_cpu(self):
        self.computer.add("Intel i5-12400 CPU")
    
    def build_memory(self):
        self.computer.add("16GB DDR4 RAM")
    
    def build_storage(self):
        self.computer.add("512GB SSD + 1TB HDD")
    
    def build_graphics_card(self):
        self.computer.add("Integrated Graphics")

# 导演类
class ComputerEngineer:
    def __init__(self):
        self.builder: ComputerBuilder = None
    
    def set_builder(self, builder: ComputerBuilder):
        self.builder = builder
    
    def build_computer(self):
        self.builder.build_cpu()
        self.builder.build_memory()
        self.builder.build_storage()
        self.builder.build_graphics_card()
        return self.builder.get_computer()
    
    def build_minimal_computer(self):
        """构建简化版电脑"""
        self.builder.build_cpu()
        self.builder.build_memory()
        return self.builder.get_computer()

# 使用
if __name__ == "__main__":
    engineer = ComputerEngineer()
    
    # 构建游戏电脑
    gaming_builder = GamingComputerBuilder()
    engineer.set_builder(gaming_builder)
    gaming_computer = engineer.build_computer()
    print("=== 游戏电脑 ===")
    print(gaming_computer)
    
    # 构建办公电脑
    office_builder = OfficeComputerBuilder()
    engineer.set_builder(office_builder)
    office_computer = engineer.build_computer()
    print("\n=== 办公电脑 ===")
    print(office_computer)
    
    # 构建简化版办公电脑
    minimal_office_computer = engineer.build_minimal_computer()
    print("\n=== 简化版办公电脑 ===")
    print(minimal_office_computer)

C++实现

cpp 复制代码
#include <iostream>
#include <memory>
#include <vector>
#include <string>

// 产品类
class Computer {
private:
    std::vector<std::string> parts;
    
public:
    void addPart(const std::string& part) {
        parts.push_back(part);
    }
    
    void listParts() const {
        std::cout << "计算机配置: ";
        for (size_t i = 0; i < parts.size(); ++i) {
            std::cout << parts[i];
            if (i != parts.size() - 1) {
                std::cout << ", ";
            }
        }
        std::cout << std::endl;
    }
};

// 抽象建造者
class ComputerBuilder {
protected:
    std::unique_ptr<Computer> computer;
    
public:
    ComputerBuilder() : computer(std::make_unique<Computer>()) {}
    virtual ~ComputerBuilder() = default;
    
    virtual void buildCPU() = 0;
    virtual void buildMemory() = 0;
    virtual void buildStorage() = 0;
    virtual void buildGraphicsCard() = 0;
    
    std::unique_ptr<Computer> getComputer() {
        auto result = std::move(computer);
        computer = std::make_unique<Computer>();  // 重置用于下次构建
        return result;
    }
};

// 具体建造者 - 游戏电脑
class GamingComputerBuilder : public ComputerBuilder {
public:
    void buildCPU() override {
        computer->addPart("Intel i9-13900K CPU");
    }
    
    void buildMemory() override {
        computer->addPart("32GB DDR5 RAM");
    }
    
    void buildStorage() override {
        computer->addPart("2TB NVMe SSD");
    }
    
    void buildGraphicsCard() override {
        computer->addPart("NVIDIA RTX 4090");
    }
};

// 具体建造者 - 办公电脑
class OfficeComputerBuilder : public ComputerBuilder {
public:
    void buildCPU() override {
        computer->addPart("Intel i5-12400 CPU");
    }
    
    void buildMemory() override {
        computer->addPart("16GB DDR4 RAM");
    }
    
    void buildStorage() override {
        computer->addPart("512GB SSD + 1TB HDD");
    }
    
    void buildGraphicsCard() override {
        computer->addPart("Integrated Graphics");
    }
};

// 导演类
class ComputerEngineer {
private:
    ComputerBuilder* builder;
    
public:
    void setBuilder(ComputerBuilder* newBuilder) {
        builder = newBuilder;
    }
    
    std::unique_ptr<Computer> buildComputer() {
        builder->buildCPU();
        builder->buildMemory();
        builder->buildStorage();
        builder->buildGraphicsCard();
        return builder->getComputer();
    }
    
    std::unique_ptr<Computer> buildMinimalComputer() {
        builder->buildCPU();
        builder->buildMemory();
        return builder->getComputer();
    }
};

// 使用
int main() {
    ComputerEngineer engineer;
    
    // 构建游戏电脑
    GamingComputerBuilder gamingBuilder;
    engineer.setBuilder(&gamingBuilder);
    auto gamingComputer = engineer.buildComputer();
    std::cout << "=== 游戏电脑 ===" << std::endl;
    gamingComputer->listParts();
    
    // 构建办公电脑
    OfficeComputerBuilder officeBuilder;
    engineer.setBuilder(&officeBuilder);
    auto officeComputer = engineer.buildComputer();
    std::cout << "\n=== 办公电脑 ===" << std::endl;
    officeComputer->listParts();
    
    // 构建简化版办公电脑
    auto minimalOfficeComputer = engineer.buildMinimalComputer();
    std::cout << "\n=== 简化版办公电脑 ===" << std::endl;
    minimalOfficeComputer->listParts();
    
    return 0;
}

3. 原型模式 (Prototype)

组件框图

bash 复制代码
┌─────────────────┐         ┌──────────────────┐
│   Client        │         │   Prototype      │
├─────────────────┤         ├──────────────────┤
│                 │───────>│+clone()          │
│                 │         └──────────────────┘
└─────────────────┘                   △
                             ┌─────────┴─────────┐
                   ┌──────────┴──────────┐ ┌─────┴────────┐
                   │ ConcretePrototype1  │ │ConcretePrototype2│
                   ├─────────────────────┤ ├────────────────┤
                   │+clone()             │ │+clone()        │
                   │-field               │ │-field          │
                   └─────────────────────┘ └────────────────┘

详细描述

问题:

需要创建的对象成本较高(如数据库操作、网络请求),或者希望避免使用子类来扩展对象创建。

解决方案:

通过复制现有对象来创建新对象,而不是通过新建类实例。

效果:

  • 优点:避免重复初始化操作,动态添加或删除产品

  • 缺点:复杂对象的克隆可能较困难,需要深拷贝考虑

Python实现

python 复制代码
import copy
from abc import ABC, abstractmethod
from typing import List, Dict

# 原型接口
class Prototype(ABC):
    @abstractmethod
    def clone(self):
        pass

# 具体原型 - 简历
class Resume(Prototype):
    def __init__(self, name: str = ""):
        self.name = name
        self.work_experience: List[str] = []
        self.skills: List[str] = []
        self.personal_info: Dict[str, str] = {}
    
    def set_personal_info(self, key: str, value: str):
        self.personal_info[key] = value
    
    def add_work_experience(self, experience: str):
        self.work_experience.append(experience)
    
    def add_skill(self, skill: str):
        self.skills.append(skill)
    
    def clone(self):
        """深拷贝克隆方法"""
        return copy.deepcopy(self)
    
    def shallow_clone(self):
        """浅拷贝克隆方法"""
        return copy.copy(self)
    
    def display(self):
        print(f"\n=== 简历: {self.name} ===")
        print("个人信息:")
        for key, value in self.personal_info.items():
            print(f"  {key}: {value}")
        
        print("工作经历:")
        for exp in self.work_experience:
            print(f"  - {exp}")
        
        print("技能:")
        for skill in self.skills:
            print(f"  - {skill}")

# 具体原型 - 图形对象
class GraphicObject(Prototype):
    def __init__(self, color: str = "black", x: int = 0, y: int = 0):
        self.color = color
        self.x = x
        self.y = y
        self.children: List[GraphicObject] = []
    
    def add_child(self, child: 'GraphicObject'):
        self.children.append(child)
    
    def clone(self):
        """深拷贝克隆,包括所有子对象"""
        return copy.deepcopy(self)
    
    def __str__(self):
        return f"GraphicObject(color={self.color}, position=({self.x},{self.y}), children={len(self.children)})"

# 原型管理器
class PrototypeManager:
    def __init__(self):
        self._prototypes: Dict[str, Prototype] = {}
    
    def register_prototype(self, name: str, prototype: Prototype):
        self._prototypes[name] = prototype
    
    def unregister_prototype(self, name: str):
        if name in self._prototypes:
            del self._prototypes[name]
    
    def clone_prototype(self, name: str) -> Prototype:
        if name in self._prototypes:
            return self._prototypes[name].clone()
        raise ValueError(f"原型 '{name}' 未注册")

# 使用
if __name__ == "__main__":
    # 创建原型简历
    original_resume = Resume("张三")
    original_resume.set_personal_info("age", "28")
    original_resume.set_personal_info("email", "zhang@email.com")
    original_resume.add_work_experience("ABC公司 - 软件工程师 (2020-2023)")
    original_resume.add_skill("Python")
    original_resume.add_skill("C++")
    
    print("=== 原始简历 ===")
    original_resume.display()
    
    # 克隆简历并修改
    cloned_resume = original_resume.clone()
    cloned_resume.name = "李四"
    cloned_resume.set_personal_info("email", "li@email.com")
    cloned_resume.add_work_experience("XYZ公司 - 高级工程师 (2023-至今)")
    cloned_resume.add_skill("Java")
    
    print("\n=== 克隆并修改后的简历 ===")
    cloned_resume.display()
    
    # 原型管理器使用
    print("\n=== 原型管理器示例 ===")
    manager = PrototypeManager()
    manager.register_prototype("standard_resume", original_resume)
    
    # 快速创建多个相似简历
    resume1 = manager.clone_prototype("standard_resume")
    resume1.name = "王五"
    resume1.display()
    
    # 图形对象克隆
    print("\n=== 图形对象克隆 ===")
    original_graphic = GraphicObject("red", 10, 20)
    child1 = GraphicObject("blue", 5, 5)
    child2 = GraphicObject("green", 15, 15)
    original_graphic.add_child(child1)
    original_graphic.add_child(child2)
    
    cloned_graphic = original_graphic.clone()
    cloned_graphic.color = "yellow"
    cloned_graphic.x = 30
    
    print(f"原始对象: {original_graphic}")
    print(f"克隆对象: {cloned_graphic}")

C++实现

cpp 复制代码
#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <unordered_map>

// 原型接口
class Prototype {
public:
    virtual ~Prototype() = default;
    virtual std::unique_ptr<Prototype> clone() const = 0;
    virtual void display() const = 0;
};

// 具体原型 - 简历
class Resume : public Prototype {
private:
    std::string name;
    std::vector<std::string> workExperience;
    std::vector<std::string> skills;
    std::unordered_map<std::string, std::string> personalInfo;
    
public:
    Resume(const std::string& name = "") : name(name) {}
    
    void setPersonalInfo(const std::string& key, const std::string& value) {
        personalInfo[key] = value;
    }
    
    void addWorkExperience(const std::string& experience) {
        workExperience.push_back(experience);
    }
    
    void addSkill(const std::string& skill) {
        skills.push_back(skill);
    }
    
    std::unique_ptr<Prototype> clone() const override {
        return std::make_unique<Resume>(*this);  // 使用拷贝构造函数
    }
    
    void display() const override {
        std::cout << "\n=== 简历: " << name << " ===" << std::endl;
        std::cout << "个人信息:" << std::endl;
        for (const auto& [key, value] : personalInfo) {
            std::cout << "  " << key << ": " << value << std::endl;
        }
        
        std::cout << "工作经历:" << std::endl;
        for (const auto& exp : workExperience) {
            std::cout << "  - " << exp << std::endl;
        }
        
        std::cout << "技能:" << std::endl;
        for (const auto& skill : skills) {
            std::cout << "  - " << skill << std::endl;
        }
    }
    
    // 拷贝构造函数
    Resume(const Resume& other)
        : name(other.name),
          workExperience(other.workExperience),
          skills(other.skills),
          personalInfo(other.personalInfo) {}
};

// 原型管理器
class PrototypeManager {
private:
    std::unordered_map<std::string, std::unique_ptr<Prototype>> prototypes;
    
public:
    void registerPrototype(const std::string& name, std::unique_ptr<Prototype> prototype) {
        prototypes[name] = std::move(prototype);
    }
    
    void unregisterPrototype(const std::string& name) {
        prototypes.erase(name);
    }
    
    std::unique_ptr<Prototype> clonePrototype(const std::string& name) {
        auto it = prototypes.find(name);
        if (it != prototypes.end()) {
            return it->second->clone();
        }
        throw std::runtime_error("原型 '" + name + "' 未注册");
    }
};

// 使用
int main() {
    // 创建原型简历
    auto originalResume = std::make_unique<Resume>("张三");
    originalResume->setPersonalInfo("age", "28");
    originalResume->setPersonalInfo("email", "zhang@email.com");
    originalResume->addWorkExperience("ABC公司 - 软件工程师 (2020-2023)");
    originalResume->addSkill("Python");
    originalResume->addSkill("C++");
    
    std::cout << "=== 原始简历 ===" << std::endl;
    originalResume->display();
    
    // 克隆简历
    auto clonedResume = originalResume->clone();
    auto* resumePtr = dynamic_cast<Resume*>(clonedResume.get());
    if (resumePtr) {
        // 注意:这里需要修改接口以支持修改,为了示例简化
        std::cout << "\n=== 克隆的简历 ===" << std::endl;
        resumePtr->display();
    }
    
    // 原型管理器使用
    std::cout << "\n=== 原型管理器示例 ===" << std::endl;
    PrototypeManager manager;
    manager.registerPrototype("standard_resume", std::move(originalResume));
    
    // 快速创建多个相似简历
    auto resume1 = manager.clonePrototype("standard_resume");
    resume1->display();
    
    return 0;
}

4. 单例模式 (Singleton)

组件框图

bash 复制代码
┌─────────────────┐
│   Singleton     │
├─────────────────┤
│-instance        │
│-data            │
├─────────────────┤
│-Singleton()     │
│+getInstance()   │
│+businessLogic() │
└─────────────────┘

详细描述

问题:

确保一个类只有一个实例,并提供一个全局访问点。

解决方案:

将构造函数私有化,提供一个静态方法返回唯一实例。

效果:

  • 优点:严格控制实例数量,全局访问点

  • 缺点:可能隐藏过度耦合,难以测试,违反单一职责原则

Python实现

python 复制代码
import threading
from typing import Dict, Any

class SingletonMeta(type):
    """单例元类,线程安全版本"""
    _instances: Dict[type, Any] = {}
    _lock: threading.Lock = threading.Lock()
    
    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls not in cls._instances:
                instance = super().__call__(*args, **kwargs)
                cls._instances[cls] = instance
        return cls._instances[cls]

# 数据库连接单例
class DatabaseConnection(metaclass=SingletonMeta):
    def __init__(self, connection_string: str = "default_connection"):
        self.connection_string = connection_string
        self.is_connected = False
        self._connection_count = 0
        print(f"初始化数据库连接: {connection_string}")
    
    def connect(self):
        if not self.is_connected:
            self.is_connected = True
            self._connection_count += 1
            print("数据库连接已建立")
        else:
            print("数据库已经连接")
    
    def disconnect(self):
        if self.is_connected:
            self.is_connected = False
            print("数据库连接已断开")
        else:
            print("数据库已经断开")
    
    def execute_query(self, query: str):
        if self.is_connected:
            print(f"执行查询: {query}")
            return f"查询结果: {query}"
        else:
            raise Exception("数据库未连接")
    
    def get_connection_count(self):
        return self._connection_count

# 配置管理器单例
class ConfigurationManager(metaclass=SingletonMeta):
    def __init__(self):
        self._config = {
            "database": {
                "host": "localhost",
                "port": 5432,
                "username": "admin"
            },
            "application": {
                "name": "MyApp",
                "version": "1.0.0"
            }
        }
        print("配置管理器初始化完成")
    
    def get(self, key: str, default=None):
        """获取配置项"""
        keys = key.split('.')
        value = self._config
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key: str, value):
        """设置配置项"""
        keys = key.split('.')
        config = self._config
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        config[keys[-1]] = value
    
    def show_config(self):
        """显示所有配置"""
        import json
        print("当前配置:")
        print(json.dumps(self._config, indent=2, ensure_ascii=False))

# 线程测试
def test_singleton_thread(thread_id: int):
    """测试多线程环境下的单例"""
    db = DatabaseConnection()
    db.connect()
    config = ConfigurationManager()
    app_name = config.get("application.name")
    print(f"线程 {thread_id} - 应用名称: {app_name}")

# 使用
if __name__ == "__main__":
    print("=== 单例模式演示 ===")
    
    # 测试数据库连接单例
    print("\n1. 数据库连接单例测试:")
    db1 = DatabaseConnection("postgresql://localhost:5432/mydb")
    db2 = DatabaseConnection("different_connection")  # 这个不会生效
    
    db1.connect()
    db2.connect()  # 实际上是同一个实例
    
    print(f"db1 is db2: {db1 is db2}")
    print(f"连接次数: {db1.get_connection_count()}")
    
    # 测试配置管理器单例
    print("\n2. 配置管理器单例测试:")
    config1 = ConfigurationManager()
    config2 = ConfigurationManager()
    
    print(f"config1 is config2: {config1 is config2}")
    
    # 获取配置
    db_host = config1.get("database.host")
    app_version = config1.get("application.version")
    print(f"数据库主机: {db_host}")
    print(f"应用版本: {app_version}")
    
    # 修改配置
    config1.set("database.port", 3306)
    config1.show_config()
    
    # 多线程测试
    print("\n3. 多线程单例测试:")
    threads = []
    for i in range(3):
        thread = threading.Thread(target=test_singleton_thread, args=(i,))
        threads.append(thread)
        thread.start()
    
    for thread in threads:
        thread.join()

C++实现

cpp 复制代码
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>

// 数据库连接单例
class DatabaseConnection {
private:
    static std::unique_ptr<DatabaseConnection> instance;
    static std::mutex mutex;
    
    std::string connectionString;
    bool isConnected;
    int connectionCount;
    
    // 私有构造函数
    DatabaseConnection(const std::string& connStr = "default_connection") 
        : connectionString(connStr), isConnected(false), connectionCount(0) {
        std::cout << "初始化数据库连接: " << connectionString << std::endl;
    }
    
public:
    // 删除拷贝构造函数和赋值操作符
    DatabaseConnection(const DatabaseConnection&) = delete;
    DatabaseConnection& operator=(const DatabaseConnection&) = delete;
    
    // 获取单例实例
    static DatabaseConnection& getInstance(const std::string& connStr = "default_connection") {
        std::lock_guard<std::mutex> lock(mutex);
        if (!instance) {
            instance = std::unique_ptr<DatabaseConnection>(new DatabaseConnection(connStr));
        }
        return *instance;
    }
    
    void connect() {
        if (!isConnected) {
            isConnected = true;
            connectionCount++;
            std::cout << "数据库连接已建立" << std::endl;
        } else {
            std::cout << "数据库已经连接" << std::endl;
        }
    }
    
    void disconnect() {
        if (isConnected) {
            isConnected = false;
            std::cout << "数据库连接已断开" << std::endl;
        } else {
            std::cout << "数据库已经断开" << std::endl;
        }
    }
    
    void executeQuery(const std::string& query) {
        if (isConnected) {
            std::cout << "执行查询: " << query << std::endl;
        } else {
            throw std::runtime_error("数据库未连接");
        }
    }
    
    int getConnectionCount() const {
        return connectionCount;
    }
    
    std::string getConnectionString() const {
        return connectionString;
    }
};

// 静态成员初始化
std::unique_ptr<DatabaseConnection> DatabaseConnection::instance = nullptr;
std::mutex DatabaseConnection::mutex;

// 配置管理器单例
class ConfigurationManager {
private:
    static ConfigurationManager* instance;
    static std::mutex mutex;
    
    std::unordered_map<std::string, std::string> config;
    
    ConfigurationManager() {
        // 默认配置
        config["database.host"] = "localhost";
        config["database.port"] = "5432";
        config["application.name"] = "MyApp";
        config["application.version"] = "1.0.0";
        std::cout << "配置管理器初始化完成" << std::endl;
    }
    
public:
    ConfigurationManager(const ConfigurationManager&) = delete;
    ConfigurationManager& operator=(const ConfigurationManager&) = delete;
    
    static ConfigurationManager& getInstance() {
        std::lock_guard<std::mutex> lock(mutex);
        if (!instance) {
            instance = new ConfigurationManager();
        }
        return *instance;
    }
    
    static void destroyInstance() {
        std::lock_guard<std::mutex> lock(mutex);
        delete instance;
        instance = nullptr;
    }
    
    std::string get(const std::string& key, const std::string& defaultValue = "") {
        auto it = config.find(key);
        if (it != config.end()) {
            return it->second;
        }
        return defaultValue;
    }
    
    void set(const std::string& key, const std::string& value) {
        config[key] = value;
    }
    
    void showConfig() {
        std::cout << "当前配置:" << std::endl;
        for (const auto& [key, value] : config) {
            std::cout << "  " << key << ": " << value << std::endl;
        }
    }
};

// 静态成员初始化
ConfigurationManager* ConfigurationManager::instance = nullptr;
std::mutex ConfigurationManager::mutex;

// 使用
int main() {
    std::cout << "=== 单例模式演示 ===" << std::endl;
    
    // 测试数据库连接单例
    std::cout << "\n1. 数据库连接单例测试:" << std::endl;
    DatabaseConnection& db1 = DatabaseConnection::getInstance("postgresql://localhost:5432/mydb");
    DatabaseConnection& db2 = DatabaseConnection::getInstance("different_connection");
    
    db1.connect();
    db2.connect();  // 实际上是同一个实例
    
    std::cout << "db1 和 db2 是同一个实例: " << (&db1 == &db2) << std::endl;
    std::cout << "连接次数: " << db1.getConnectionCount() << std::endl;
    std::cout << "连接字符串: " << db1.getConnectionString() << std::endl;
    
    // 测试配置管理器单例
    std::cout << "\n2. 配置管理器单例测试:" << std::endl;
    ConfigurationManager& config1 = ConfigurationManager::getInstance();
    ConfigurationManager& config2 = ConfigurationManager::getInstance();
    
    std::cout << "config1 和 config2 是同一个实例: " << (&config1 == &config2) << std::endl;
    
    // 获取和修改配置
    std::string dbHost = config1.get("database.host");
    std::string appVersion = config1.get("application.version");
    std::cout << "数据库主机: " << dbHost << std::endl;
    std::cout << "应用版本: " << appVersion << std::endl;
    
    config1.set("database.port", "3306");
    config1.showConfig();
    
    // 清理
    ConfigurationManager::destroyInstance();
    
    return 0;
}

模式对比总结

模式 主要目的 适用场景 关键特性
抽象工厂 创建产品族 需要系列相关产品 工厂接口,产品兼容性
建造者 复杂对象构建 构建过程复杂,步骤多 分步构建,相同过程不同表示
原型 对象克隆 创建成本高,避免子类 克隆方法,深拷贝/浅拷贝
单例 唯一实例 需要全局访问点,控制实例数量 私有构造,静态实例,线程安全

这些创建型模式都解决了对象创建的不同方面问题,在实际开发中可以根据具体需求选择合适的模式。

相关推荐
Misnearch1 天前
原型模式了解
原型模式
charlie1145141912 天前
精读C++20设计模式——创造型设计模式:单例模式
c++·学习·单例模式·设计模式·c++20
charlie1145141913 天前
精读《C++20设计模式》——创造型设计模式:原型模式
设计模式·程序设计·原型模式·c++20
Mr_WangAndy4 天前
C++设计模式_创建型模式_单件模式
c++·单例模式·设计模式
舒克起飞了4 天前
设计模式——单例模式
java·单例模式·设计模式
Mr_WangAndy5 天前
C++设计模式_创建型模式_原型模式Prototype
c++·设计模式·原型模式
奔跑吧邓邓子5 天前
【C++实战㊷】C++ 原型模式实战:从概念到高效应用
c++·实战·原型模式
Hello.Reader5 天前
用 Flink DataStream API 搭建流式 ETL从无状态到有状态、从单流到连接流
flink·etl·原型模式
笨手笨脚の6 天前
设计模式-原型模式
java·设计模式·创建型设计模式·原型模式