🚀【设计模式实战】原型模式 + 工厂模式:AI Agent 配置中心
场景:多智能体协作系统的动态 Agent 创建与管理
AI 应用中,尤其是 多智能体系统(Multi-Agent System) 中,我们需要动态创建各种类型的 AI Agent,例如:
- 客服助手
- 数据分析师
- 内容生成器
- 安全审核员
- 任务协调器
每个 Agent 拥有:
- 独特的 提示词模板(Prompt Template)
- 所需的 工具集(Tools)(如搜索、数据库、计算器)
- 记忆机制(短期/长期记忆)
- 行为策略(自主决策等级)
- LLM 模型配置(温度、最大 token 数等)
如果每次创建都重新解析配置文件或构建复杂对象,性能差且难以维护。
通过 原型模式 + 工厂模式 + 注册表机制 ,我们可以实现:
✅ 高性能克隆
✅ 动态热更新 Agent 配置
✅ 统一配置管理
✅ 类型安全的 Agent 创建
一、系统架构设计
+------------------+ +-----------------------+
| AgentFactory |---->| AgentPrototypeRegistry|
| (工厂) | | (原型注册中心) |
+------------------+ +-----------------------+
| |
v v
+------------------+ +------------------------+
| Client Code | | AgentPrototype |
| (业务系统) | | (可克隆接口) |
+------------------+ +------------------------+
|
v
+----------------------------+
| 具体 Agent 类型 |
| - CustomerServiceAgent |
| - DataAnalysisAgent |
| - ContentGenerationAgent |
+----------------------------+
二、核心代码实现(Java)
1. 抽象原型接口
java
public interface AgentPrototype extends Cloneable {
AgentPrototype clone() throws CloneNotSupportedException;
String getAgentType();
void run(String input);
}
2. 具体 Agent 原型类
💬 客服助手 Agent
java
import java.util.*;
public class CustomerServiceAgent implements AgentPrototype {
private String id;
private String name;
private String promptTemplate;
private List<String> tools; // 使用的工具列表
private double temperature;
private boolean enableMemory;
public CustomerServiceAgent() {
this.id = generateId();
this.name = "客服助手";
this.temperature = 0.5;
this.enableMemory = true;
this.tools = Arrays.asList("knowledge_base_search", "ticket_system_api");
this.promptTemplate = """
你是一名专业的客服助手,请礼貌、耐心地回答用户问题。
如果无法解决,请引导用户提交工单。
用户问题:%s
""";
}
private String generateId() {
return "AGENT_CS_" + System.currentTimeMillis();
}
@Override
public AgentPrototype clone() throws CloneNotSupportedException {
CustomerServiceAgent clone = (CustomerServiceAgent) super.clone();
clone.id = generateId(); // 新实例新ID
clone.tools = new ArrayList<>(this.tools); // 深拷贝可变对象
return clone;
}
@Override
public String getAgentType() {
return "CUSTOMER_SERVICE";
}
@Override
public void run(String input) {
String finalPrompt = String.format(promptTemplate, input);
System.out.println("🎯 Agent启动: " + name);
System.out.println("📝 提示词: " + finalPrompt);
System.out.println("🔧 使用工具: " + tools);
System.out.println("🌡️ 温度: " + temperature);
System.out.println("🧠 记忆启用: " + enableMemory);
System.out.println("✅ 模拟响应: 您好,已收到您的问题,请稍等,正在为您查询...");
System.out.println("-".repeat(50));
}
// 可动态调整行为
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public void setEnableMemory(boolean enableMemory) {
this.enableMemory = enableMemory;
}
}
📊 数据分析 Agent
java
public class DataAnalysisAgent implements AgentPrototype {
private String id;
private String name;
private String promptTemplate;
private List<String> dataSources;
private boolean autoVisualization;
public DataAnalysisAgent() {
this.id = generateId();
this.name = "数据分析助手";
this.autoVisualization = true;
this.dataSources = Arrays.asList("sales_db", "user_behavior_log");
this.promptTemplate = """
请分析以下数据问题,并生成可视化建议:
问题:%s
数据源:%s
要求:输出 SQL 示例 + 图表类型建议
""";
}
private String generateId() {
return "AGENT_DA_" + System.nanoTime();
}
@Override
public AgentPrototype clone() throws CloneNotSupportedException {
DataAnalysisAgent clone = (DataAnalysisAgent) super.clone();
clone.id = generateId();
clone.dataSources = new ArrayList<>(this.dataSources);
return clone;
}
@Override
public String getAgentType() {
return "DATA_ANALYSIS";
}
@Override
public void run(String input) {
String finalPrompt = String.format(promptTemplate, input, String.join(",", dataSources));
System.out.println("🎯 Agent启动: " + name);
System.out.println("📝 提示词: " + finalPrompt);
System.out.println("📊 数据源: " + dataSources);
System.out.println("🖼️ 自动可视化: " + autoVisualization);
System.out.println("✅ 模拟响应: 已生成分析报告,建议使用柱状图展示月度销售额...");
System.out.println("-".repeat(50));
}
public void setAutoVisualization(boolean autoVisualization) {
this.autoVisualization = autoVisualization;
}
}
✍️ 内容生成 Agent
java
public class ContentGenerationAgent implements AgentPrototype {
private String id;
private String name;
private String writingStyle;
private int wordCount;
private String tone;
public ContentGenerationAgent() {
this.id = generateId();
this.name = "内容生成助手";
this.writingStyle = "professional";
this.tone = "neutral";
this.wordCount = 500;
}
private String generateId() {
return "AGENT_CG_" + (int)(Math.random() * 10000);
}
@Override
public AgentPrototype clone() throws CloneNotSupportedException {
ContentGenerationAgent clone = (ContentGenerationAgent) super.clone();
clone.id = generateId();
return clone;
}
@Override
public String getAgentType() {
return "CONTENT_GENERATION";
}
@Override
public void run(String input) {
String prompt = String.format(
"请以%s风格、%s语气撰写一篇%d字的文章,主题:%s",
writingStyle, tone, wordCount, input
);
System.out.println("🎯 Agent启动: " + name);
System.out.println("📝 生成指令: " + prompt);
System.out.println("✅ 模拟响应: 正在调用LLM生成内容...");
System.out.println("-".repeat(50));
}
public void setWritingStyle(String writingStyle) {
this.writingStyle = writingStyle;
}
public void setTone(String tone) {
this.tone = tone;
}
public void setWordCount(int wordCount) {
this.wordCount = wordCount;
}
}
3. 原型注册表(集中管理所有 Agent 原型)
java
import java.util.HashMap;
import java.util.Map;
public class AgentPrototypeRegistry {
private final Map<String, AgentPrototype> registry = new HashMap<>();
public void register(String type, AgentPrototype prototype) {
registry.put(type, prototype);
System.out.println("✅ 注册 Agent 原型: " + type);
}
public AgentPrototype create(String type) throws CloneNotSupportedException {
AgentPrototype prototype = registry.get(type);
if (prototype != null) {
System.out.println("⚡ 克隆 Agent 实例: " + type);
return prototype.clone();
}
throw new IllegalArgumentException("未注册的 Agent 类型: " + type);
}
// 支持运行时热更新(比如通过配置中心推送新模板)
public void updatePrototype(String type, AgentPrototype newPrototype) {
if (registry.containsKey(type)) {
registry.put(type, newPrototype);
System.out.println("🔄 更新 Agent 原型: " + type);
} else {
System.out.println("⚠️ Agent 类型不存在,无法更新: " + type);
}
}
public void listAllAgents() {
System.out.println("\n📋 当前注册的 Agent 类型:");
registry.keySet().forEach(System.out::println);
}
}
4. Agent 工厂(提供类型安全的创建接口)
java
public class AgentFactory {
private final AgentPrototypeRegistry registry;
public AgentFactory(AgentPrototypeRegistry registry) {
this.registry = registry;
}
public CustomerServiceAgent createCustomerServiceAgent() {
try {
return (CustomerServiceAgent) registry.create("CUSTOMER_SERVICE");
} catch (Exception e) {
throw new RuntimeException("创建客服Agent失败", e);
}
}
public DataAnalysisAgent createDataAnalysisAgent() {
try {
return (DataAnalysisAgent) registry.create("DATA_ANALYSIS");
} catch (Exception e) {
throw new RuntimeException("创建数据分析Agent失败", e);
}
}
public ContentGenerationAgent createContentGenerationAgent() {
try {
return (ContentGenerationAgent) registry.create("CONTENT_GENERATION");
} catch (Exception e) {
throw new RuntimeException("创建内容生成Agent失败", e);
}
}
}
5. 客户端使用示例
java
public class AIAgentSystem {
public static void main(String[] args) {
try {
// 1. 初始化注册表
AgentPrototypeRegistry registry = new AgentPrototypeRegistry();
// 2. 注册基础 Agent 原型
registry.register("CUSTOMER_SERVICE", new CustomerServiceAgent());
registry.register("DATA_ANALYSIS", new DataAnalysisAgent());
registry.register("CONTENT_GENERATION", new ContentGenerationAgent());
// 3. 创建工厂
AgentFactory factory = new AgentFactory(registry);
// 4. 使用工厂创建 Agent 实例
System.out.println("🎮 开始创建 AI Agent 实例...\n");
CustomerServiceAgent csAgent1 = factory.createCustomerServiceAgent();
csAgent1.run("我的订单还没发货");
CustomerServiceAgent csAgent2 = factory.createCustomerServiceAgent();
csAgent2.setTemperature(0.7); // 更有创造性
csAgent2.run("如何退换货?");
DataAnalysisAgent daAgent = factory.createDataAnalysisAgent();
daAgent.setAutoVisualization(false);
daAgent.run("上季度华东区销售额趋势");
ContentGenerationAgent cgAgent = factory.createContentGenerationAgent();
cgAgent.setTone("humorous");
cgAgent.setWordCount(800);
cgAgent.run("人工智能对未来教育的影响");
// 5. 演示热更新(模拟配置中心推送)
System.out.println("🔄 模拟热更新:修改客服Agent提示词...");
CustomerServiceAgent updatedCS = new CustomerServiceAgent();
updatedCS.setTemperature(0.3); // 更确定性
registry.updatePrototype("CUSTOMER_SERVICE", updatedCS);
CustomerServiceAgent csAgent3 = factory.createCustomerServiceAgent();
csAgent3.run("账户被锁定了怎么办?");
// 列出所有类型
registry.listAllAgents();
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、输出示例
✅ 注册 Agent 原型: CUSTOMER_SERVICE
✅ 注册 Agent 原型: DATA_ANALYSIS
✅ 注册 Agent 原型: CONTENT_GENERATION
🎮 开始创建 AI Agent 实例...
⚡ 克隆 Agent 实例: CUSTOMER_SERVICE
🎯 Agent启动: 客服助手
📝 提示词: 你是一名专业的客服助手,请礼貌、耐心地回答用户问题...
✅ 模拟响应: 您好,已收到您的问题,请稍等,正在为您查询...
--------------------------------------------------
⚡ 克隆 Agent 实例: CUSTOMER_SERVICE
🎯 Agent启动: 客服助手
🌡️ 温度: 0.7
✅ 模拟响应: 您好,已收到您的问题,请稍等,正在为您查询...
--------------------------------------------------
⚡ 克隆 Agent 实例: DATA_ANALYSIS
🎯 Agent启动: 数据分析助手
🖼️ 自动可视化: false
✅ 模拟响应: 已生成分析报告,建议使用柱状图展示月度销售额...
--------------------------------------------------
⚡ 克隆 Agent 实例: CONTENT_GENERATION
🎯 Agent启动: 内容生成助手
📝 生成指令: 请以professional风格、humorous语气撰写一篇800字的文章...
✅ 模拟响应: 正在调用LLM生成内容...
--------------------------------------------------
🔄 模拟热更新:修改客服Agent提示词...
🔄 更新 Agent 原型: CUSTOMER_SERVICE
⚡ 克隆 Agent 实例: CUSTOMER_SERVICE
🌡️ 温度: 0.3
✅ 模拟响应: 您好,已收到您的问题,请稍等,正在为您查询...
--------------------------------------------------
📋 当前注册的 Agent 类型:
CUSTOMER_SERVICE
DATA_ANALYSIS
CONTENT_GENERATION
四、设计优势总结
特性 | 说明 |
---|---|
⚡ 高性能创建 | 避免重复构建复杂对象,直接克隆原型 |
🔧 动态热更新 | 运行时替换原型,无需重启服务 |
🧩 解耦配置与创建 | 工厂屏蔽细节,客户端只关心"要什么" |
📦 集中配置管理 | 所有 Agent 模板统一注册,便于治理 |
🔄 支持个性化定制 | 克隆后可修改参数,实现差异化行为 |
五、可扩展方向
- 对接 配置中心(如 Nacos、Apollo)实现远程热更新
- 添加 Agent 版本管理(v1, v2)
- 支持 JSON/YAML 配置加载 构建原型
- 引入 缓存机制 提升克隆性能
- 结合 责任链模式 实现 Agent 编排
💡 一句话总结 :
在 AI Agent 系统中,原型模式 + 工厂模式 是实现"快速实例化 + 灵活配置 + 动态演进"的黄金组合,特别适合需要高频创建相似智能体的场景。