正在加载,请稍候…

软件架构模式:分层架构、六边形架构与整洁架构

比较并实现分层架构、六边形架构和整洁架构,为你的项目选择合适的架构模式

软件架构模式:分层架构、六边形架构与整洁架构

软件架构模式:分层架构、六边形架构与整洁架构

架构定义了代码的组织方式以及依赖关系的流向。

分层架构

表示层      → 控制器、API 处理器
业务层      → 服务、用例
数据层      → 仓库、ORM
基础设施层  → 数据库、外部服务
// 分层示例
// 第1层:控制器(表示层)
class UserController {
  constructor(private userService: UserService) {}

  async createUser(req: Request, res: Response) {
    const user = await this.userService.create(req.body);
    res.status(201).json(user);
  }
}

// 第2层:服务(业务层)
class UserService {
  constructor(private userRepo: UserRepository) {}

  async create(data: CreateUserDto): Promise<User> {
    await this.validateEmail(data.email);
    return this.userRepo.save(new User(data));
  }
}

// 第3层:仓库(数据层)
class UserRepository {
  async save(user: User): Promise<User> {
    return this.db.users.create(user);
  }
}

软件架构模式:分层架构、六边形架构与整洁架构示意图

六边形架构(端口与适配器)

将领域与基础设施关注点隔离。

// 领域核心(无外部依赖)
class UserService {
  constructor(
    private userPort: UserPort,       // 端口(接口)
    private emailPort: EmailPort      // 端口(接口)
  ) {}

  async register(email: string, password: string): Promise<User> {
    const exists = await this.userPort.findByEmail(email);
    if (exists) throw new DuplicateEmailError();
    const user = User.create(email, password);
    await this.userPort.save(user);
    await this.emailPort.sendWelcome(email);
    return user;
  }
}

// 端口(由领域定义的接口)
interface UserPort {
  findByEmail(email: string): Promise<User | null>;
  save(user: User): Promise<void>;
}

interface EmailPort {
  sendWelcome(email: string): Promise<void>;
}

// 适配器(实现端口,依赖外部库)
class PostgresUserAdapter implements UserPort {
  constructor(private db: PrismaClient) {}

  async findByEmail(email: string) {
    return this.db.user.findUnique({ where: { email } });
  }

  async save(user: User) {
    await this.db.user.upsert({ where: { id: user.id }, create: user, update: user });
  }
}

class SendGridEmailAdapter implements EmailPort {
  async sendWelcome(email: string) {
    await sendGrid.send({ to: email, subject: 'Welcome!', text: '...' });
  }
}

软件架构模式:分层架构、六边形架构与整洁架构示意图

整洁架构

// 实体 - 企业业务规则
class User {
  private constructor(
    readonly id: string,
    readonly email: Email,
    readonly createdAt: Date
  ) {}

  static create(email: string): User {
    return new User(crypto.randomUUID(), Email.of(email), new Date());
  }
}

// 用例 - 应用业务规则
class RegisterUserUseCase {
  constructor(
    private userRepo: UserRepository,
    private emailService: EmailService,
    private eventBus: EventBus
  ) {}

  async execute(request: RegisterUserRequest): Promise<RegisterUserResponse> {
    const existing = await this.userRepo.findByEmail(request.email);
    if (existing) return { success: false, error: 'Email already registered' };

    const user = User.create(request.email);
    await this.userRepo.save(user);
    await this.emailService.sendWelcome(user.email.toString());
    await this.eventBus.publish(new UserRegistered(user.id));

    return { success: true, userId: user.id };
  }
}

// 接口适配器 - 控制器、展示器、网关
class RegisterUserController {
  constructor(private useCase: RegisterUserUseCase) {}

  async handle(req: Request, res: Response) {
    const result = await this.useCase.execute({ email: req.body.email });
    if (!result.success) return res.status(400).json({ error: result.error });
    res.status(201).json({ id: result.userId });
  }
}

软件架构模式:分层架构、六边形架构与整洁架构示意图

何时使用每种架构

模式 最佳适用场景
分层架构 简单的 CRUD 应用、小型团队
六边形架构 多种适配器(CLI + HTTP + 事件)、高可测试性
整洁架构 复杂领域、长期维护的系统

架构是工具,不是教条——根据你的上下文选择。