---
description: 面向对象编程设计原则和模式应用
globs: ["**/*.ts", "**/services/**/*", "**/stores/**/*"]
alwaysApply: false
---

# 面向对象编程设计规范

## 🎯 核心设计原则

### SOLID 原则强制执行

```typescript
// ✅ 单一职责原则 (SRP)
// 每个类只负责一个功能
class UserValidator {
  validate(user: IUser): boolean {
    return user.email !== undefined && /@/.test(user.email);
  }
}

class UserRepository {
  async save(user: IUser): Promise<IUser> {
    // 只负责数据持久化
  }
  
  async findById(id: string): Promise<IUser | null> {
    // 只负责数据查询
  }
}

// ❌ 违反单一职责原则
class UserService {
  validate(user: IUser): boolean { /* 验证逻辑 */ }
  save(user: IUser): Promise<IUser> { /* 保存逻辑 */ }
  sendEmail(user: IUser): Promise<void> { /* 邮件逻辑 */ }
  generateReport(): Promise<Report> { /* 报告逻辑 */ }
}
```

```typescript
// ✅ 开闭原则 (OCP) - 对扩展开放，对修改关闭
abstract class PaymentProcessor {
  abstract processPayment(amount: number): Promise<PaymentResult>;
}

class CreditCardProcessor extends PaymentProcessor {
  async processPayment(amount: number): Promise<PaymentResult> {
    // 信用卡支付实现
  }
}

class AlipayProcessor extends PaymentProcessor {
  async processPayment(amount: number): Promise<PaymentResult> {
    // 支付宝支付实现
  }
}

// ✅ 依赖倒置原则 (DIP)
interface IUserRepository {
  findById(id: string): Promise<IUser | null>;
  save(user: IUser): Promise<IUser>;
}

class UserService {
  constructor(private userRepository: IUserRepository) {}
  
  async getUser(id: string): Promise<IUser | null> {
    return this.userRepository.findById(id);
  }
}
```

## 🏗️ 设计模式应用

### 工厂模式
```typescript
// ✅ 使用工厂模式创建复杂对象
interface IPaymentGateway {
  processPayment(amount: number): Promise<PaymentResult>;
}

class StripeGateway implements IPaymentGateway {
  constructor(private apiKey: string) {}
  
  async processPayment(amount: number): Promise<PaymentResult> {
    // Stripe 支付实现
  }
}

class AlipayGateway implements IPaymentGateway {
  constructor(private config: AlipayConfig) {}
  
  async processPayment(amount: number): Promise<PaymentResult> {
    // 支付宝支付实现
  }
}

class PaymentGatewayFactory {
  static create(type: PaymentType, config: PaymentConfig): IPaymentGateway {
    switch (type) {
      case 'stripe':
        return new StripeGateway(config.stripeKey);
      case 'alipay':
        return new AlipayGateway(config.alipayConfig);
      default:
        throw new Error(`不支持的支付类型: ${type}`);
    }
  }
}

// 使用示例
const gateway = PaymentGatewayFactory.create('stripe', config);
await gateway.processPayment(100);
```

### 策略模式
```typescript
// ✅ 策略模式处理不同算法
interface ISortingStrategy<T> {
  sort(items: T[]): T[];
}

class QuickSortStrategy<T> implements ISortingStrategy<T> {
  sort(items: T[]): T[] {
    // 快速排序实现
  }
}

class MergeSortStrategy<T> implements ISortingStrategy<T> {
  sort(items: T[]): T[] {
    // 归并排序实现
  }
}

class SortContext<T> {
  constructor(private strategy: ISortingStrategy<T>) {}
  
  setStrategy(strategy: ISortingStrategy<T>): void {
    this.strategy = strategy;
  }
  
  executeSort(items: T[]): T[] {
    return this.strategy.sort(items);
  }
}

// 使用示例
const sortContext = new SortContext(new QuickSortStrategy());
const sortedItems = sortContext.executeSort(items);
```

## 🔄 组合优于继承

```typescript
// ✅ 使用组合而非继承
interface ILogger {
  log(message: string): void;
  error(message: string): void;
}

interface IValidator<T> {
  validate(data: T): boolean;
}

class ConsoleLogger implements ILogger {
  log(message: string): void {
    console.log(message);
  }
  
  error(message: string): void {
    console.error(message);
  }
}

class UserValidator implements IValidator<IUser> {
  validate(user: IUser): boolean {
    return user.email !== undefined && /@/.test(user.email);
  }
}

// ✅ 通过组合实现功能
class UserService {
  constructor(
    private logger: ILogger,
    private validator: IValidator<IUser>,
    private repository: IUserRepository
  ) {}
  
  async createUser(userData: IUser): Promise<IUser> {
    if (!this.validator.validate(userData)) {
      this.logger.error('用户数据验证失败');
      throw new Error('无效的用户数据');
    }
    
    this.logger.log('开始创建用户');
    const user = await this.repository.save(userData);
    this.logger.log(`用户创建成功: ${user.id}`);
    
    return user;
  }
}
```

## 🎨 Vue 3 组合式 API 中的 OOP 思想

### Composables 作为服务类
```typescript
// ✅ Composables 实现服务模式
export function useUserManagement() {
  // 私有状态
  const users = ref<IUser[]>([]);
  const isLoading = ref<boolean>(false);
  const error = ref<string | null>(null);
  
  // 私有方法
  const validateUser = (user: IUser): boolean => {
    return user.email !== undefined && /@/.test(user.email);
  };
  
  const logOperation = (operation: string, userId: string): void => {
    console.log(`${operation} 用户: ${userId}`);
  };
  
  // 公共方法
  const fetchUsers = async (): Promise<void> => {
    isLoading.value = true;
    error.value = null;
    
    try {
      const response = await UserService.getAll();
      users.value = response.data;
    } catch (err) {
      error.value = err.message || '获取用户列表失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };
  
  const createUser = async (userData: IUser): Promise<IUser> => {
    if (!validateUser(userData)) {
      throw new Error('用户数据验证失败');
    }
    
    try {
      logOperation('创建', userData.id);
      const response = await UserService.create(userData);
      users.value.push(response.data);
      return response.data;
    } catch (err) {
      error.value = err.message || '创建用户失败';
      throw err;
    }
  };
  
  // 计算属性
  const userCount = computed(() => users.value.length);
  const adminUsers = computed(() => 
    users.value.filter(user => user.role === 'admin')
  );
  
  // 返回公共接口
  return {
    // 状态
    users: readonly(users),
    isLoading: readonly(isLoading),
    error: readonly(error),
    
    // 计算属性
    userCount,
    adminUsers,
    
    // 方法
    fetchUsers,
    createUser,
  };
}
```

## 🔍 代码审核与面向对象思想

**[必需]** 代码生成完成后必须检查是否符合面向对象编程思想。

### OOP 审核检查清单
- [ ] **单一职责原则**：每个类/函数只负责一个功能
- [ ] **开闭原则**：对扩展开放，对修改关闭
- [ ] **里氏替换原则**：子类可以替换父类
- [ ] **接口隔离原则**：接口应该小而专一
- [ ] **依赖倒置原则**：依赖抽象而非具体实现
- [ ] **封装性**：私有成员使用 `private` 或 `_` 前缀
- [ ] **继承和组合**：优先使用组合而非继承
- [ ] **设计模式应用**：合理使用工厂、单例、观察者等模式

### 代码质量检查
- [ ] 检查未使用的变量、函数、导入
- [ ] 识别重复的代码块和业务逻辑
- [ ] 验证函数参数是否都被使用
- [ ] 检查是否有可复用的代码
- [ ] 函数行数不超过 50 行
- [ ] 函数参数不超过 5 个
- [ ] 嵌套层级不超过 4 层

### 自动审核触发机制
- **触发条件**：仅对代码文件（.ts, .vue, .js, .tsx, .jsx）修改时触发
- **排除条件**：规则文件（.mdc, .md, .txt, .json）修改时不触发
- **防死循环**：审核过程本身不触发新的审核
- **审核时机**：代码生成或修改完成后立即执行

## 🎯 面向对象编程最佳实践

### 必需配置项
- ✅ 遵循 SOLID 设计原则
- ✅ 使用工厂模式创建复杂对象
- ✅ 优先使用组合而非继承
- ✅ 使用依赖注入模式
- ✅ 设计清晰的接口

### 参考文件
- `services/user.service.ts` - 服务类示例
- `factories/user.factory.ts` - 工厂模式示例
- `interfaces/user.interface.ts` - 接口定义示例
- `composables/useAuth.ts` - 组合式函数示例