🏗️ 建造者模式 (Builder Pattern)
📖 模式简介
建造者模式是一种创建型设计模式,它允许你分步骤创建复杂对象。该模式允许你使用相同的创建代码生成不同类型和形式的对象。建造者模式将复杂对象的构建过程抽象出来,使得同样的构建过程可以创建不同的表示。
🔍 问题场景
想象你正在开发一个游戏,需要创建各种类型的角色。每个角色都有很多属性:
- 基础属性:姓名、职业、等级、生命值、魔法值
- 装备属性:武器、护甲、饰品
- 技能属性:主动技能、被动技能
- 外观属性:头发颜色、眼睛颜色、皮肤颜色等
❌ 没有使用设计模式的实现
#include <iostream>
#include <string>
#include <vector>
// 糟糕的实现方式
class GameCharacter {
private:
std::string name;
std::string profession;
int level;
int health;
int mana;
std::string weapon;
std::string armor;
std::string accessory;
std::vector<std::string> activeSkills;
std::vector<std::string> passiveSkills;
std::string hairColor;
std::string eyeColor;
std::string skinColor;
bool hasMount;
std::string mountType;
bool hasPet;
std::string petType;
public:
// 噩梦般的构造函数
GameCharacter(const std::string& name, const std::string& profession,
int level, int health, int mana, const std::string& weapon,
const std::string& armor, const std::string& accessory,
const std::vector<std::string>& activeSkills,
const std::vector<std::string>& passiveSkills,
const std::string& hairColor, const std::string& eyeColor,
const std::string& skinColor, bool hasMount = false,
const std::string& mountType = "", bool hasPet = false,
const std::string& petType = "")
: name(name), profession(profession), level(level), health(health),
mana(mana), weapon(weapon), armor(armor), accessory(accessory),
activeSkills(activeSkills), passiveSkills(passiveSkills),
hairColor(hairColor), eyeColor(eyeColor), skinColor(skinColor),
hasMount(hasMount), mountType(mountType), hasPet(hasPet), petType(petType) {
}
void display() const {
std::cout << "Character: " << name << " (" << profession << ")" << std::endl;
std::cout << "Level: " << level << ", HP: " << health << ", MP: " << mana << std::endl;
std::cout << "Equipment: " << weapon << ", " << armor << ", " << accessory << std::endl;
// ... 更多输出
}
};
// 使用示例 - 参数地狱
void badExample() {
std::vector<std::string> skills1 = {
"Fireball", "Lightning"};
std::vector<std::string> passives1 = {
"Magic Mastery"};
// 17个参数!这还不包括可能的扩展
GameCharacter mage("Gandalf", "Wizard", 50, 800, 1200, "Magic Staff",
"Robe of Power", "Ring of Wisdom", skills1, passives1,
"White", "Blue", "Pale", true, "Unicorn", false, "");
std::vector<std::string> skills2 = {
"Slash", "Shield Bash"};
std::vector<std::string> passives2 = {
"Heavy Armor Mastery", "Weapon Expert"};
GameCharacter warrior("Conan", "Warrior", 45, 1500, 300, "Great Sword",
"Plate Mail", "Strength Amulet", skills2, passives2,
"Black", "Brown", "Tanned", true, "War Horse", true, "Wolf");
}
😰 这种实现的问题:
- 构造函数参数过多:17个参数,极易出错
- 参数顺序混乱:很容易传错参数位置
- 可读性极差:调用时完全不知道每个参数的含义
- 扩展困难:添加新属性需要修改构造函数
- 默认值处理复杂:大量可选参数导致重载爆炸
- 对象创建过程不灵活:必须一次性提供所有参数