2025-07-08
设计模式
0

目录

🔥23 种设计模式藏着的商业智慧💡
一个创业公司的成长故事
设计模式与创业场景对应流程图
第一阶段:团队搭建——创建型
第二阶段:架构升级——结构性
第三阶段:高效运营——行为型
23种设计模式详解
1. 工厂模式 - 批量招聘员工
2. 抽象工厂模式 - 按岗位分级招聘
3. 建造者模式 - 组建完整项目组
4. 原型模式 - 复制核心人才
5. 单例模式 - 确保唯一CEO
6. 适配器模式 - 并购公司系统兼容
7. 桥接模式 - 多业务线独立发展
8. 组合模式 - 树形组织架构管理
9. 装饰器模式 - 动态调整员工待遇
10. 外观模式 - 统一对外接口
11. 享元模式 - 共享办公资源
12. 代理模式 - CEO事务代理
13. 责任链模式 - 多级审批流程
14. 命令模式 - 任务指令封装
15. 解释器模式 - 规则引擎解析
16. 迭代器模式 - 全员奖金发放
17. 中介者模式 - 跨部门协调
18. 备忘录模式 - 系统灾难恢复
19. 观察者模式 - 政策通知机制
20. 状态模式 - 请假状态流转
21. 策略模式 - 营销策略切换
22. 模板方法模式 - 标准化入职
23. 访问者模式 - 差异化统计
总结
设计模式顺口溜

🔥23 种设计模式藏着的商业智慧💡

一个创业公司的成长故事

张伟从大厂辞职创业时,怀揣着改变世界的梦想,却不知前方有多少坑等着他。起初,他需要快速搭建团队:用"工厂模式"批量招聘基础员工,通过"抽象工厂"按岗位分级引进人才,像"建造者模式"一样精心组建完整项目组,遇到核心人才就用"原型模式"快速复制,而CEO职位自然要像"单例模式"确保唯一。当公司扩张到200人时,架构升级迫在眉睫:用"适配器模式"兼容并购公司的系统,通过"桥接模式"让多业务线独立发展,采用"组合模式"构建树形组织架构,用"装饰器模式"动态调整员工待遇,建立"外观模式"统一对外接口,实施"享元模式"共享办公资源,并引入"代理模式"处理CEO事务。当日活用户突破100万后,高效运营成为关键:建立"责任链模式"处理多级审批,用"命令模式"封装任务指令,开发"解释器模式"解析规则引擎,通过"迭代器模式"发放全员奖金,采用"中介者模式"协调跨部门合作,建立"备忘录模式"应对系统灾难,实施"观察者模式"推送政策通知,用"状态模式"管理请假流程,灵活切换"策略模式"调整营销策略,标准化"模板方法模式"规范入职流程,最后用"访问者模式"实现差异化统计。这一路走来,张伟发现,那些看似枯燥的设计模式,实则蕴含着深刻的商业智慧。

设计模式与创业场景对应流程图

第一阶段:团队搭建——创建型

image.png

第二阶段:架构升级——结构性

image.png

第三阶段:高效运营——行为型

image.png

image.png

23种设计模式详解

1. 工厂模式 - 批量招聘员工

场景:需要快速批量生产相同类型的员工对象

java
public class EmployeeFactory { public Employee createEmployee(String type) { if ("developer".equals(type)) { return new Developer(); } else if ("designer".equals(type)) { return new Designer(); } return null; } } // 使用 EmployeeFactory factory = new EmployeeFactory(); Employee dev1 = factory.createEmployee("developer"); Employee designer1 = factory.createEmployee("designer");

2. 抽象工厂模式 - 按岗位分级招聘

场景:需要按不同级别(初级/高级)招聘完整团队

java
interface TeamFactory { Developer createDeveloper(); Designer createDesigner(); Tester createTester(); } class JuniorTeamFactory implements TeamFactory { public Developer createDeveloper() { return new JuniorDeveloper(); } public Designer createDesigner() { return new JuniorDesigner(); } public Tester createTester() { return new JuniorTester(); } } class SeniorTeamFactory implements TeamFactory { public Developer createDeveloper() { return new SeniorDeveloper(); } // ...其他高级职位创建方法 } interface Developer { String getRole(); } interface Designer { String getRole(); } interface Tester { String getRole(); } class JuniorDeveloper implements Developer { public String getRole() { return "初级开发"; } } class SeniorDeveloper implements Developer { public String getRole() { return "高级开发"; } } class JuniorDesigner implements Designer { public String getRole() { return "初级设计"; } } class SeniorDesigner implements Designer { public String getRole() { return "高级设计"; } } class JuniorTester implements Tester { public String getRole() { return "初级测试"; } } class SeniorTester implements Tester { public String getRole() { return "高级测试"; } } // 抽象工厂模式使用示例 public class TeamBuildingDemo { public static void main(String[] args) { // 1. 选择团队级别 TeamFactory juniorFactory = new JuniorTeamFactory(); TeamFactory seniorFactory = new SeniorTeamFactory(); // 2. 组建初级团队 System.out.println("=== 组建初级团队 ==="); buildTeam(juniorFactory); // 3. 组建高级团队 System.out.println("\n=== 组建高级团队 ==="); buildTeam(seniorFactory); } // 通用团队构建方法 static void buildTeam(TeamFactory factory) { Developer dev = factory.createDeveloper(); Designer designer = factory.createDesigner(); Tester tester = factory.createTester(); System.out.println("团队成员:" + dev.getRole() + " + " + designer.getRole() + " + " + tester.getRole()); } }

3. 建造者模式 - 组建完整项目组

场景:逐步构建复杂项目团队对象

java
public class ProjectTeam { private List<Developer> developers; private List<Designer> designers; // ...其他成员 public static class Builder { private ProjectTeam team = new ProjectTeam(); public Builder addDeveloper(Developer dev) { team.developers.add(dev); return this; } public Builder addDesigner(Designer designer) { team.designers.add(designer); return this; } public ProjectTeam build() { return team; } } } // 使用 ProjectTeam team = new ProjectTeam.Builder() .addDeveloper(new SeniorDeveloper()) .addDesigner(new SeniorDesigner()) .build();

4. 原型模式 - 复制核心人才

场景:快速复制优秀员工模板

java
public abstract class Employee implements Cloneable { protected String name; protected String position; public Employee clone() { try { return (Employee) super.clone(); } catch (CloneNotSupportedException e) { return null; } } } // 使用 Employee starEmployee = new StarDeveloper(); Employee clone1 = starEmployee.clone(); clone1.setName("Clone Dev 1");

5. 单例模式 - 确保唯一CEO

场景:保证公司只有一个CEO实例

java
public class CEO { private static CEO instance; private CEO() {} public static CEO getInstance() { if (instance == null) { synchronized (CEO.class) { if (instance == null) { instance = new CEO(); } } } return instance; } } // 使用 CEO ceo1 = CEO.getInstance(); CEO ceo2 = CEO.getInstance(); System.out.println(ceo1 == ceo2); // true

6. 适配器模式 - 并购公司系统兼容

场景:让不同公司系统能够协同工作

java
interface OurSystem { void processData(String data); } class AcquiredSystem { void handleData(XMLData data) { /*...*/ } } class SystemAdapter implements OurSystem { private AcquiredSystem acquiredSystem; public SystemAdapter(AcquiredSystem system) { this.acquiredSystem = system; } public void processData(String data) { XMLData xml = convertToXML(data); acquiredSystem.handleData(xml); } private XMLData convertToXML(String data) { /*...*/ } } class XMLData { // 假设这是被适配系统需要的XML数据结构 } class SystemAdapter implements OurSystem { private AcquiredSystem acquiredSystem; public SystemAdapter(AcquiredSystem system) { this.acquiredSystem = system; } public void processData(String data) { System.out.println("适配器:将字符串转换为XML"); XMLData xml = convertToXML(data); acquiredSystem.handleData(xml); } private XMLData convertToXML(String data) { System.out.println("转换数据: " + data + " → XML格式"); return new XMLData(); } } // 适配器模式使用示例 public class AdapterDemo { public static void main(String[] args) { // 1. 创建被适配的旧系统 AcquiredSystem oldSystem = new AcquiredSystem(); // 2. 创建适配器(包装旧系统) OurSystem adaptedSystem = new SystemAdapter(oldSystem); // 3. 使用新接口调用旧系统 System.out.println("=== 数据处理 ==="); adaptedSystem.processData("JSON格式数据"); } }

7. 桥接模式 - 多业务线独立发展

场景:将业务抽象与实现解耦

java
abstract class BusinessLine { protected Product product; public BusinessLine(Product product) { this.product = product; } abstract void operate(); } interface Product { void produce(); } class ECommerceLine extends BusinessLine { public ECommerceLine(Product product) { super(product); } void operate() { System.out.println("电商业务线运营:"); product.produce(); } } class PhysicalProduct implements Product { public void produce() { System.out.println("生产实体商品"); } } class DigitalProduct implements Product { public void produce() { System.out.println("生成数字商品"); } } class CloudServiceLine extends BusinessLine { public CloudServiceLine(Product product) { super(product); } void operate() { System.out.println("云服务业务线运营:"); product.produce(); } } // 桥接模式使用示例 public class BridgeDemo { public static void main(String[] args) { // 1. 创建具体产品 Product physical = new PhysicalProduct(); Product digital = new DigitalProduct(); // 假设有DigitalProduct实现类 // 2. 创建业务线并组合产品 BusinessLine ecommerce = new ECommerceLine(physical); BusinessLine cloud = new CloudServiceLine(digital); // 假设有CloudServiceLine实现类 // 3. 运营业务线 System.out.println("=== 业务运营 ==="); ecommerce.operate(); System.out.println("---"); cloud.operate(); } }

8. 组合模式 - 树形组织架构管理

场景:统一处理单个员工和部门

java
interface OrganizationComponent { void display(); } class Employee implements OrganizationComponent { private String name; public void display() { System.out.println("员工: " + name); } } class Department implements OrganizationComponent { private List<OrganizationComponent> members = new ArrayList<>(); public void add(OrganizationComponent comp) { members.add(comp); } public void display() { for (OrganizationComponent comp : members) { comp.display(); } } } class Employee implements OrganizationComponent { private String name; public Employee(String name) { this.name = name; } public void display() { System.out.println("员工: " + name); } public void add(OrganizationComponent comp) { throw new UnsupportedOperationException("员工不能添加成员"); } public void remove(OrganizationComponent comp) { throw new UnsupportedOperationException("员工不能移除成员"); } } class Department implements OrganizationComponent { private String name; private List<OrganizationComponent> members = new ArrayList<>(); public Department(String name) { this.name = name; } public void display() { System.out.println("\n部门: " + name); for (OrganizationComponent comp : members) { comp.display(); } } public void add(OrganizationComponent comp) { members.add(comp); } public void remove(OrganizationComponent comp) { members.remove(comp); } } // 组合模式使用示例 public class OrganizationDemo { public static void main(String[] args) { // 1. 创建员工个体 OrganizationComponent dev1 = new Employee("张三(前端开发)"); OrganizationComponent dev2 = new Employee("李四(后端开发)"); OrganizationComponent designer = new Employee("王五(UI设计师)"); // 2. 创建部门组合 OrganizationComponent techDepartment = new Department("技术部"); techDepartment.add(dev1); techDepartment.add(dev2); techDepartment.add(designer); // 3. 创建跨部门项目组 OrganizationComponent projectTeam = new Department("A项目组"); projectTeam.add(techDepartment); projectTeam.add(new Employee("赵六(产品经理)")); projectTeam.add(new Employee("钱七(市场专员)")); // 4. 显示完整组织架构 System.out.println("=== 公司组织架构 ==="); projectTeam.display(); // 5. 创业公司特色:动态调整组织 System.out.println("\n=== 架构调整后 ==="); techDepartment.remove(designer); // 设计师调岗 projectTeam.add(new Employee("孙八(新招实习生)")); projectTeam.display(); } }

9. 装饰器模式 - 动态调整员工待遇

场景:动态添加员工福利

java
interface Employee { double getSalary(); String getBenefits(); } class BasicEmployee implements Employee { public double getSalary() { return 10000; } public String getBenefits() { return "基本社保"; } } abstract class EmployeeDecorator implements Employee { protected Employee employee; public EmployeeDecorator(Employee employee) { this.employee = employee; } } class BonusDecorator extends EmployeeDecorator { public BonusDecorator(Employee employee) { super(employee); } public double getSalary() { return employee.getSalary() + 2000; } public String getBenefits() { return employee.getBenefits() + ", 季度奖金"; } } class GymMembershipDecorator extends EmployeeDecorator { public GymMembershipDecorator(Employee employee) { super(employee); } public String getBenefits() { return employee.getBenefits() + ", 健身房会员"; } } class StockOptionDecorator extends EmployeeDecorator { public StockOptionDecorator(Employee employee) { super(employee); } public double getSalary() { return employee.getSalary() + 5000; // 股票期权价值 } public String getBenefits() { return employee.getBenefits() + ", 股票期权"; } } // 装饰器模式使用示例 public class EmployeeBenefitsDemo { public static void main(String[] args) { // 1. 创建基础员工 Employee entryLevel = new BasicEmployee(); System.out.println("初级员工: 薪资=" + entryLevel.getSalary() + ", 福利=" + entryLevel.getBenefits()); // 2. 添加奖金装饰器 Employee withBonus = new BonusDecorator(entryLevel); System.out.println("\n+奖金后: 薪资=" + withBonus.getSalary() + ", 福利=" + withBonus.getBenefits()); // 3. 创业公司特色:叠加多重福利 Employee fullPackage = new StockOptionDecorator( new GymMembershipDecorator( new BonusDecorator(entryLevel))); System.out.println("\n豪华套餐: 薪资=" + fullPackage.getSalary() + ", 福利=" + fullPackage.getBenefits()); } }

10. 外观模式 - 统一对外接口

场景:简化复杂系统对外接口

java
class CompanyFacade { private HRSystem hr; private FinanceSystem finance; private ProductSystem product; public CompanyFacade() { hr = new HRSystem(); finance = new FinanceSystem(); product = new ProductSystem(); } public void newHireProcess(String name) { hr.registerEmployee(name); finance.setupSalaryAccount(name); product.assignStarterProject(name); } } // 使用 CompanyFacade facade = new CompanyFacade(); facade.newHireProcess("张三");

11. 享元模式 - 共享办公资源

场景:共享可复用的办公设备

java
class OfficeResource { private final String resourceType; public OfficeResource(String type) { this.resourceType = type; } void use(String employeeName) { System.out.println(employeeName + " 使用 " + resourceType); } } class ResourceFactory { private Map<String, OfficeResource> resources = new HashMap<>(); public OfficeResource getResource(String type) { OfficeResource resource = resources.get(type); if (resource == null) { resource = new OfficeResource(type); resources.put(type, resource); } return resource; } } // 使用 ResourceFactory factory = new ResourceFactory(); OfficeResource printer = factory.getResource("打印机"); printer.use("李四");

12. 代理模式 - CEO事务代理

场景:控制对CEO的访问

java
interface CEO { void handleRequest(String request); } class RealCEO implements CEO { public void handleRequest(String request) { System.out.println("CEO处理请求: " + request); } } class CEOProxy implements CEO { private RealCEO realCEO; public void handleRequest(String request) { if (realCEO == null) { realCEO = new RealCEO(); } if (isImportant(request)) { realCEO.handleRequest(request); } else { System.out.println("代理过滤请求: " + request); } } private boolean isImportant(String request) { return request.contains("重要"); } } // 代理模式使用示例 public class CEORequestDemo { public static void main(String[] args) { // 1. 创建代理CEO(秘书过滤请求) CEO ceoProxy = new CEOProxy(); // 2. 模拟各种请求场景 System.out.println("=== 普通工作日请求处理 ==="); ceoProxy.handleRequest("预约下周会议"); // 被过滤 ceoProxy.handleRequest("重要客户合作提案"); // 转交CEO ceoProxy.handleRequest("员工团建方案审批"); // 被过滤 ceoProxy.handleRequest("重要融资谈判准备"); // 转交CEO // 3. 创业公司特殊场景:直接访问真实CEO System.out.println("\n=== 紧急情况直接联系CEO ==="); RealCEO realCEO = new RealCEO(); realCEO.handleRequest("服务器崩溃紧急处理"); } }

13. 责任链模式 - 多级审批流程

场景:请求沿审批链传递

java
abstract class Approver { protected Approver next; public void setNext(Approver next) { this.next = next; } public abstract void processRequest(LeaveRequest request); } class Manager extends Approver { public void processRequest(LeaveRequest request) { if (request.getDays() <= 3) { System.out.println("经理批准 " + request); } else if (next != null) { next.processRequest(request); } } } class Director extends Approver { public void processRequest(LeaveRequest request) { if (request.getDays() <= 10) { System.out.println("总监批准 " + request); } else if (next != null) { next.processRequest(request); } } } class CEO extends Approver { public void processRequest(LeaveRequest request) { if (request.getDays() <= 30) { System.out.println("CEO批准 " + request); } else { System.out.println(request + " 超过权限,需要董事会决议"); } } } class LeaveRequest { private String name; private int days; private String reason; public LeaveRequest(String name, int days, String reason) { this.name = name; this.days = days; this.reason = reason; } public int getDays() { return days; } @Override public String toString() { return String.format("[%s 请假%d天 原因:%s]", name, days, reason); } } // 责任链模式使用示例 public class LeaveApprovalDemo { public static void main(String[] args) { // 1. 创建审批链(经理 -> 总监 -> CEO) Approver manager = new Manager(); Approver director = new Director(); Approver ceo = new CEO(); // 假设有CEO审批类 manager.setNext(director); director.setNext(ceo); // 2. 创建不同天数的请假请求 LeaveRequest shortLeave = new LeaveRequest("张三", 2, "感冒休息"); LeaveRequest mediumLeave = new LeaveRequest("李四", 5, "参加婚礼"); LeaveRequest longLeave = new LeaveRequest("王五", 15, "海外旅行"); // 3. 提交审批 System.out.println("=== 请假审批开始 ==="); manager.processRequest(shortLeave); System.out.println("---"); manager.processRequest(mediumLeave); System.out.println("---"); manager.processRequest(longLeave); } }

14. 命令模式 - 任务指令封装

场景:将请求封装为对象

java
interface Command { void execute(); } class Task { private String name; public Task(String name) { this.name = name; } public void complete() { System.out.println("完成任务: " + name); } } class TaskCommand implements Command { private Task task; public TaskCommand(Task task) { this.task = task; } public void execute() { task.complete(); } } class Scheduler { private List<Command> commands = new ArrayList<>(); public void addCommand(Command cmd) { commands.add(cmd); } public void run() { for (Command cmd : commands) { cmd.execute(); } } } // 命令模式使用示例 public class CommandPatternDemo { public static void main(String[] args) { // 1. 创建任务调度器(Invoker) Scheduler scheduler = new Scheduler(); // 2. 创建具体任务(Receiver) Task task1 = new Task("设计登录页面"); Task task2 = new Task("开发用户API"); Task task3 = new Task("测试支付功能"); // 3. 将任务封装为命令对象 Command designCommand = new TaskCommand(task1); Command developCommand = new TaskCommand(task2); Command testCommand = new TaskCommand(task3); // 4. 创业公司晨会布置任务 System.out.println("=== 晨会任务分配 ==="); scheduler.addCommand(designCommand); scheduler.addCommand(developCommand); // 5. 紧急插入新任务(灵活扩展) scheduler.addCommand(testCommand); // 6. 执行所有任务 System.out.println("=== 开始执行任务 ==="); scheduler.run(); // 7. 创业公司特色:撤销功能扩展 System.out.println("\n=== 添加撤销功能示例 ==="); Command undoableCommand = new TaskCommand(task1) { @Override public void execute() { super.execute(); System.out.println("(此任务可撤销)"); } }; scheduler.addCommand(undoableCommand); scheduler.run(); } }

15. 解释器模式 - 规则引擎解析

场景:解析业务规则语法

java
interface Expression { boolean interpret(String context); } class TerminalExpression implements Expression { private String data; public TerminalExpression(String data) { this.data = data; } public boolean interpret(String context) { return context.contains(data); } } class OrExpression implements Expression { private Expression expr1; private Expression expr2; public OrExpression(Expression expr1, Expression expr2) { this.expr1 = expr1; this.expr2 = expr2; } public boolean interpret(String context) { return expr1.interpret(context) || expr2.interpret(context); } } // 使用: 构建规则 "VIP用户 或 订单金额大于1000" Expression vip = new TerminalExpression("VIP用户"); Expression bigOrder = new TerminalExpression("订单>1000"); Expression rule = new OrExpression(vip, bigOrder); System.out.println(rule.interpret("VIP用户")); // true

16. 迭代器模式 - 全员奖金发放

场景:遍历员工集合

java
interface EmployeeIterator { boolean hasNext(); Employee next(); } class EmployeeCollection { private Employee[] employees; public EmployeeCollection(Employee[] employees) { this.employees = employees; } public EmployeeIterator createIterator() { return new EmployeeArrayIterator(employees); } } class EmployeeArrayIterator implements EmployeeIterator { private Employee[] employees; private int position = 0; public EmployeeArrayIterator(Employee[] employees) { this.employees = employees; } public boolean hasNext() { return position < employees.length; } public Employee next() { return employees[position++]; } } // 使用 EmployeeCollection collection = new EmployeeCollection(employees); EmployeeIterator iterator = collection.createIterator(); while (iterator.hasNext()) { payBonus(iterator.next()); }

17. 中介者模式 - 跨部门协调

场景:减少部门间直接依赖

java
interface Mediator { void notify(Department sender, String event); } class ConcreteMediator implements Mediator { private Development development; private Marketing marketing; public void setDepartments(Development dev, Marketing mkt) { this.development = dev; this.marketing = mkt; } public void notify(Department sender, String event) { if (sender == development && event.equals("新版本发布")) { marketing.prepareCampaign(); } } } abstract class Department { protected Mediator mediator; public Department(Mediator mediator) { this.mediator = mediator; } } class Development extends Department { public Development(Mediator mediator) { super(mediator); } public void releaseVersion() { System.out.println("开发部发布新版本"); mediator.notify(this, "新版本发布"); } } class Marketing extends Department { public Marketing(Mediator mediator) { super(mediator); } public void prepareCampaign() { System.out.println("市场部准备标准推广方案"); } } class Finance extends Department { public Finance(Mediator mediator) { super(mediator); } } // 使用示例 public class DepartmentCollaborationDemo { public static void main(String[] args) { // 1. 创建协调中心(中介者) ConcreteMediator mediator = new ConcreteMediator(); // 2. 创建各部门并注册到中介者 Development devTeam = new Development(mediator); Marketing mktTeam = new Marketing(mediator) { public void prepareCampaign() { System.out.println("市场部启动紧急推广计划:社交媒体+线下活动"); } }; mediator.setDepartments(devTeam, mktTeam); // 3. 创业公司典型协作场景 System.out.println("=== 新产品发布流程 ==="); devTeam.releaseVersion(); // 自动触发市场部行动 // 4. 扩展更多部门协作 System.out.println("\n=== 跨部门扩展 ==="); Finance finance = new Finance(mediator) { public void budgetApproval() { System.out.println("财务部批准营销预算"); mediator.notify(this, "预算批准"); } }; mediator.setDepartments(devTeam, mktTeam); // 保持原有关系 // 动态响应 mediator.notify(finance, "预算批准"); // 模拟财务事件 // 5. 创业公司紧急协作场景 System.out.println("\n=== 危机处理 ==="); mediator.notify(devTeam, "系统崩溃"); // 需要扩展中介者处理逻辑 } }

18. 备忘录模式 - 系统灾难恢复

场景:保存和恢复系统状态

java
class SystemState { private String dbVersion; private String configHash; public SystemState(String dbVersion, String configHash) { this.dbVersion = dbVersion; this.configHash = configHash; } public String getDbVersion() { return dbVersion; } public String getConfigHash() { return configHash; } } class SystemMemento { private SystemState state; public SystemMemento(SystemState state) { this.state = state; } public SystemState getState() { return state; } } class ProductionSystem { private SystemState state; public SystemMemento save() { return new SystemMemento(state); } public void restore(SystemMemento memento) { this.state = memento.getState(); } } // 使用示例 public class SystemBackupDemo { public static void main(String[] args) { // 1. 创建生产系统并设置初始状态 ProductionSystem productionSystem = new ProductionSystem(); SystemState initialState = new SystemState("MySQL-5.7", "config-v1.0"); productionSystem.restore(new SystemMemento(initialState)); // 2. 创建备份管理员(CareTaker角色) List<SystemMemento> backupArchives = new ArrayList<>(); // 3. 周一早上备份系统 System.out.println("=== 周一 09:00 进行系统备份 ==="); backupArchives.add(productionSystem.save()); printSystemState(productionSystem); // 4. 周二系统升级 System.out.println("\n=== 周二 系统升级到 v2.0 ==="); productionSystem.restore(new SystemMemento( new SystemState("MySQL-8.0", "config-v2.0"))); printSystemState(productionSystem); // 5. 周三发现升级问题,决定回滚 System.out.println("\n=== 周三 发现兼容性问题,准备回滚 ==="); System.out.println("回滚前状态:"); printSystemState(productionSystem); System.out.println("\n执行回滚到周一备份..."); productionSystem.restore(backupArchives.get(0)); System.out.println("回滚后状态:"); printSystemState(productionSystem); // 6. 创业公司特殊场景:灾难恢复演练 System.out.println("\n=== 灾难恢复演练 ==="); SystemMemento emergencyBackup = productionSystem.save(); // 模拟系统崩溃 productionSystem.restore(new SystemMemento( new SystemState("Corrupted-DB", "Broken-Config"))); System.out.println("模拟崩溃后状态:"); printSystemState(productionSystem); // 从紧急备份恢复 System.out.println("\n从紧急备份恢复..."); productionSystem.restore(emergencyBackup); System.out.println("恢复后状态:"); printSystemState(productionSystem); } private static void printSystemState(ProductionSystem system) { // 通过反射获取状态(实际项目中应该有getState方法) try { Field stateField = ProductionSystem.class.getDeclaredField("state"); stateField.setAccessible(true); SystemState state = (SystemState) stateField.get(system); System.out.println("当前系统状态: " + "数据库=" + state.getDbVersion() + ", 配置=" + state.getConfigHash()); } catch (Exception e) { e.printStackTrace(); } } }

19. 观察者模式 - 政策通知机制

场景:通知所有员工政策变更

java
interface Observer { void update(String policy); } interface Subject { void register(Observer o); void unregister(Observer o); void notifyObservers(); } class HRDepartment implements Subject { private List<Observer> employees = new ArrayList<>(); private String newPolicy; public void register(Observer o) { employees.add(o); } public void unregister(Observer o) { employees.remove(o); } public void notifyObservers() { for (Observer o : employees) { o.update(newPolicy); } } public void setNewPolicy(String policy) { this.newPolicy = policy; notifyObservers(); } } class Employee implements Observer { private String name; public Employee(String name) { this.name = name; } public void update(String policy) { System.out.println(name + " 收到新政策: " + policy); } } // 使用示例 public class PolicyNotificationDemo { public static void main(String[] args) { // 1. 创建HR部门(主题) HRDepartment hr = new HRDepartment(); // 2. 员工注册为观察者 Employee emp1 = new Employee("张伟(CEO)"); Employee emp2 = new Employee("李娜(CTO)"); Employee emp3 = new Employee("王强(开发)"); hr.register(emp1); hr.register(emp2); hr.register(emp3); // 3. 发布新政策(自动通知所有员工) System.out.println("=== 发布考勤新规 ==="); hr.setNewPolicy("即日起实施弹性工作制"); // 4. 新员工入职后注册 Employee emp4 = new Employee("赵敏(新晋设计师)"); hr.register(emp4); // 5. 发布第二个政策(新人也会收到) System.out.println("\n=== 发布福利政策 ==="); hr.setNewPolicy("新增年度健康体检福利"); // 6. 员工离职取消注册 hr.unregister(emp2); // 7. 发布第三个政策(离职员工不再接收) System.out.println("\n=== 发布培训计划 ==="); hr.setNewPolicy("下周举行技术分享会"); // 8. 创业公司特殊场景:紧急全员通知 System.out.println("\n=== 紧急通知 ==="); hr.setNewPolicy("⚠️ 明日服务器维护,全员远程办公"); } }

20. 状态模式 - 请假状态流转

场景:根据状态改变行为

java
interface LeaveState { void handleRequest(LeaveRequest request); } class PendingState implements LeaveState { public void handleRequest(LeaveRequest request) { System.out.println("请假申请待审批"); request.setState(new ApprovedState()); } } class ApprovedState implements LeaveState { public void handleRequest(LeaveRequest request) { System.out.println("请假已批准"); } } class RejectedState implements LeaveState { public void handleRequest(LeaveRequest request) { System.out.println("请假被拒绝"); } } class LeaveRequest { private LeaveState state; public LeaveRequest() { state = new PendingState(); } public void setState(LeaveState state) { this.state = state; } public void process() { state.handleRequest(this); } } // 使用示例 public class LeaveRequestDemo { public static void main(String[] args) { // 1. 员工提交请假申请 LeaveRequest request = new LeaveRequest(); System.out.println("=== 员工提交请假申请 ==="); request.process(); // 初始状态为待审批 // 2. 模拟审批通过场景 System.out.println("\n=== 经理审批通过 ==="); request.process(); // 自动转为批准状态 // 3. 新建一个被拒绝的案例 System.out.println("\n=== 另一个请假案例 ==="); LeaveRequest rejectedRequest = new LeaveRequest(); rejectedRequest.setState(new RejectedState()); // 直接设置为拒绝状态 rejectedRequest.process(); // 4. 创业公司特殊场景:CEO特批 System.out.println("\n=== CEO特批案例 ==="); LeaveRequest ceoRequest = new LeaveRequest(); ceoRequest.process(); // 初始状态 // 自定义直接批准状态(跳过经理审批) ceoRequest.setState(new ApprovedState() { @Override public void handleRequest(LeaveRequest request) { System.out.println("CEO特批通过"); } }); ceoRequest.process(); } }

21. 策略模式 - 营销策略切换

场景:运行时切换算法

java
interface MarketingStrategy { void executeCampaign(); } class SocialMediaStrategy implements MarketingStrategy { public void executeCampaign() { System.out.println("在社交媒体上开展营销活动"); } } class EmailStrategy implements MarketingStrategy { public void executeCampaign() { System.out.println("通过电子邮件开展营销活动"); } } class MarketingContext { private MarketingStrategy strategy; public void setStrategy(MarketingStrategy strategy) { this.strategy = strategy; } public void execute() { strategy.executeCampaign(); } } // 使用 MarketingContext context = new MarketingContext(); context.setStrategy(new SocialMediaStrategy()); context.execute(); context.setStrategy(new EmailStrategy()); context.execute();

22. 模板方法模式 - 标准化入职

场景:定义算法骨架

java
abstract class OnboardingProcess { // 模板方法 public final void onboard() { preparePaperwork(); setupWorkstation(); conductTraining(); if (needsTechnicalTraining()) { conductTechnicalTraining(); } completeProcess(); } abstract void conductTraining(); void preparePaperwork() { System.out.println("准备劳动合同和保密协议"); } void setupWorkstation() { System.out.println("设置办公桌和电脑"); } boolean needsTechnicalTraining() { return true; } void conductTechnicalTraining() { System.out.println("进行技术培训"); } void completeProcess() { System.out.println("完成入职流程"); } } class DeveloperOnboarding extends OnboardingProcess { void conductTraining() { System.out.println("进行开发规范培训"); } } // 使用示例 public class OnboardingDemo { public static void main(String[] args) { System.out.println("=== 标准员工入职流程 ==="); OnboardingProcess standardProcess = new OnboardingProcess() { void conductTraining() { System.out.println("进行公司文化培训"); } }; standardProcess.onboard(); System.out.println("\n=== 开发人员入职流程 ==="); OnboardingProcess devProcess = new DeveloperOnboarding(); devProcess.onboard(); System.out.println("\n=== 设计师入职流程(自定义技术培训) ==="); OnboardingProcess designerProcess = new OnboardingProcess() { void conductTraining() { System.out.println("进行设计规范培训"); } // 重写钩子方法 boolean needsTechnicalTraining() { return false; // 设计师不需要单独的技术培训 } }; designerProcess.onboard(); } }

23. 访问者模式 - 差异化统计

场景:对不同类型的员工执行不同操作

java
interface EmployeeVisitor { void visit(Developer dev); void visit(Designer designer); void visit(Manager manager); } interface EmployeeElement { void accept(EmployeeVisitor visitor); } class Developer implements EmployeeElement { private int codeLines; public Developer(int lines) { this.codeLines = lines; } public int getCodeLines() { return codeLines; } public void accept(EmployeeVisitor visitor) { visitor.visit(this); } } class PerformanceVisitor implements EmployeeVisitor { public void visit(Developer dev) { System.out.println("开发者绩效: " + dev.getCodeLines() + " 行代码"); } public void visit(Designer designer) { System.out.println("设计师绩效: 设计稿评估"); } public void visit(Manager manager) { System.out.println("经理绩效: 团队表现评估"); } } // 使用 EmployeeElement[] staff = {new Developer(5000), new Designer(), new Manager()}; PerformanceVisitor visitor = new PerformanceVisitor(); for (EmployeeElement employee : staff) { employee.accept(visitor); }

总结

23种设计模式就像23种商业智慧,贯穿了创业公司的整个生命周期:

  1. 创建型模式是团队组建的艺术:工厂模式批量生产、抽象工厂构建体系、建造者模式精心组装、原型模式快速复制、单例模式确保唯一。

  2. 结构型模式是架构设计的哲学:适配器兼容差异、桥接模式连接抽象与实现、组合模式统一整体与部分、装饰器动态扩展、外观模式简化接口、享元模式共享资源、代理模式控制访问。

  3. 行为型模式是高效运营的秘诀:责任链传递请求、命令模式封装操作、解释器解析规则、迭代器遍历集合、中介者解耦交互、备忘录保存状态、观察者通知变化、状态模式管理流转、策略模式切换算法、模板方法定义骨架、访问者差异化处理。

掌握这些模式,创业者就能像架构师设计系统一样设计自己的商业帝国,在复杂多变的创业环境中游刃有余。

设计模式顺口溜

工厂抽象建团队,原型单例保唯一
适配桥接组架构,装饰外观享代理
责任命令解规则,迭代中介备忘录
观察状态策略变,模板访问各不同
二十三种设计法,创业路上好帮手