مقدمه: اهمیت معماری نرم‌افزار

معماری نرم‌افزار پایه و اساس هر سیستم نرم‌افزاری موفق است. یک معماری خوب می‌تواند تفاوت بین یک پروژه قابل نگهداری و مقیاس‌پذیر با یک پروژه پر از مشکلات و باگ‌های غیرقابل حل باشد. در این مقاله به بررسی کامل اصول معماری نرم‌افزار و الگوهای طراحی می‌پردازیم.

اصول SOLID

اصول SOLID پنج اصل اساسی در برنامه‌نویسی شیءگرا هستند که توسط رابرت سی. مارتین معرفی شدند:

۱. اصل تک مسئولیتی (Single Responsibility Principle - SRP)

// نادرست - کلاس مسئولیت‌های زیادی دارد
class UserManager {
  saveUser(user: User): void { /* ذخیره در دیتابیس */ }
  sendEmail(user: User, message: string): void { /* ارسال ایمیل */ }
  validateUser(user: User): boolean { /* اعتبارسنجی */ }
  generateReport(user: User): Report { /* تولید گزارش */ }
}

// درست - هر کلاس یک مسئولیت دارد
class UserRepository {
  save(user: User): void { /* ذخیره در دیتابیس */ }
  findById(id: number): User { /* پیدا کردن کاربر */ }
}

class EmailService {
  send(to: string, subject: string, body: string): void { /* ارسال ایمیل */ }
}

class UserValidator {
  validate(user: User): ValidationResult { /* اعتبارسنجی */ }
}

class ReportGenerator {
  generate(user: User): Report { /* تولید گزارش */ }
}

۲. اصل باز-بسته (Open-Closed Principle - OCP)

// نادرست - برای اضافه کردن فرمت جدید باید کد را تغییر دهیم
class ReportExporter {
  export(report: Report, format: string): void {
    if (format === "pdf") {
      // کد تولید PDF
    } else if (format === "excel") {
      // کد تولید Excel
    } else if (format === "csv") {
      // کد تولید CSV
    }
  }
}

// درست - با اضافه شدن فرمت جدید، کد موجود تغییر نمی‌کند
interface ExportStrategy {
  export(report: Report): void;
}

class PdfExportStrategy implements ExportStrategy {
  export(report: Report): void {
    // کد تولید PDF
  }
}

class ExcelExportStrategy implements ExportStrategy {
  export(report: Report): void {
    // کد تولید Excel
  }
}

class CsvExportStrategy implements ExportStrategy {
  export(report: Report): void {
    // کد تولید CSV
  }
}

class ReportExporter {
  private strategies: Map = new Map();
  
  registerStrategy(format: string, strategy: ExportStrategy): void {
    this.strategies.set(format, strategy);
  }
  
  export(report: Report, format: string): void {
    const strategy = this.strategies.get(format);
    if (strategy) {
      strategy.export(report);
    } else {
      throw new Error(`فرمت ${format} پشتیبانی نمی‌شود`);
    }
  }
}

// استفاده
const exporter = new ReportExporter();
exporter.registerStrategy("pdf", new PdfExportStrategy());
exporter.registerStrategy("excel", new ExcelExportStrategy());
exporter.registerStrategy("csv", new CsvExportStrategy());

۳. اصل جایگزینی لیسکوف (Liskov Substitution Principle - LSP)

// نادرست - زیرکلاس رفتار والد را تغییر می‌دهد
class Rectangle {
  protected width: number;
  protected height: number;
  
  setWidth(width: number): void {
    this.width = width;
  }
  
  setHeight(height: number): void {
    this.height = height;
  }
  
  getArea(): number {
    return this.width * this.height;
  }
}

class Square extends Rectangle {
  setWidth(width: number): void {
    this.width = width;
    this.height = width; // تغییر رفتار غیرمنتظره
  }
  
  setHeight(height: number): void {
    this.height = height;
    this.width = height; // تغییر رفتار غیرمنتظره
  }
}

// درست - رابط مشترک با رفتار قابل پیش‌بینی
interface Shape {
  getArea(): number;
}

class Rectangle implements Shape {
  constructor(private width: number, private height: number) {}
  
  getArea(): number {
    return this.width * this.height;
  }
}

class Square implements Shape {
  constructor(private side: number) {}
  
  getArea(): number {
    return this.side * this.side;
  }
}

۴. اصل جداسازی رابط (Interface Segregation Principle - ISP)

// نادرست - رابط بزرگ با متدهای غیرمرتبط
interface Worker {
  work(): void;
  eat(): void;
  sleep(): void;
  code(): void;
  design(): void;
  test(): void;
}

// درست - رابط‌های کوچک و متمرکز
interface Workable {
  work(): void;
}

interface Eatable {
  eat(): void;
}

interface Sleepable {
  sleep(): void;
}

interface Coder {
  code(): void;
}

interface Designer {
  design(): void;
}

interface Tester {
  test(): void;
}

class Developer implements Workable, Eatable, Sleepable, Coder {
  work(): void { /* کار کردن */ }
  eat(): void { /* خوردن */ }
  sleep(): void { /* خوابیدن */ }
  code(): void { /* کدنویسی */ }
}

class Designer implements Workable, Eatable, Sleepable, Designer {
  work(): void { /* کار کردن */ }
  eat(): void { /* خوردن */ }
  sleep(): void { /* خوابیدن */ }
  design(): void { /* طراحی */ }
}

۵. اصل وارونگی وابستگی (Dependency Inversion Principle - DIP)

// نادرست - وابستگی به پیاده‌سازی مشخص
class EmailService {
  send(email: string, message: string): void {
    // ارسال ایمیل
  }
}

class NotificationService {
  private emailService: EmailService;
  
  constructor() {
    this.emailService = new EmailService();
  }
  
  sendNotification(user: User, message: string): void {
    this.emailService.send(user.email, message);
  }
}

// درست - وابستگی به انتزاع
interface MessageSender {
  send(to: string, message: string): void;
}

class EmailService implements MessageSender {
  send(to: string, message: string): void {
    // ارسال ایمیل
  }
}

class SmsService implements MessageSender {
  send(to: string, message: string): void {
    // ارسال SMS
  }
}

class PushNotificationService implements MessageSender {
  send(to: string, message: string): void {
    // ارسال نوتیفیکیشن
  }
}

class NotificationService {
  constructor(private messageSender: MessageSender) {}
  
  sendNotification(user: User, message: string): void {
    this.messageSender.send(user.contact, message);
  }
}

// استفاده با Dependency Injection
const emailService = new EmailService();
const notificationService = new NotificationService(emailService);

الگوهای طراحی (Design Patterns)

الگوهای خلاقانه (Creational Patterns)

۱. Singleton (تک‌نمونه)

class DatabaseConnection {
  private static instance: DatabaseConnection;
  private connection: any;
  
  private constructor() {
    // اتصال به دیتابیس
    this.connection = this.connect();
  }
  
  public static getInstance(): DatabaseConnection {
    if (!DatabaseConnection.instance) {
      DatabaseConnection.instance = new DatabaseConnection();
    }
    return DatabaseConnection.instance;
  }
  
  private connect(): any {
    // منطق اتصال به دیتابیس
    console.log("اتصال به دیتابیس برقرار شد");
    return { /* شیء اتصال */ };
  }
  
  public query(sql: string): any {
    // اجرای کوئری
    return this.connection.execute(sql);
  }
  
  public close(): void {
    // بستن اتصال
    console.log("اتصال به دیتابیس بسته شد");
  }
}

// استفاده
const db1 = DatabaseConnection.getInstance();
const db2 = DatabaseConnection.getInstance();
console.log(db1 === db2); // true

۲. Factory Method (روش کارخانه)

interface PaymentProcessor {
  process(amount: number): boolean;
}

class CreditCardProcessor implements PaymentProcessor {
  process(amount: number): boolean {
    console.log(`پرداخت ${amount} تومان با کارت اعتباری`);
    return true;
  }
}

class PayPalProcessor implements PaymentProcessor {
  process(amount: number): boolean {
    console.log(`پرداخت ${amount} تومان با PayPal`);
    return true;
  }
}

class CryptoProcessor implements PaymentProcessor {
  process(amount: number): boolean {
    console.log(`پرداخت ${amount} تومان با رمزارز`);
    return true;
  }
}

abstract class PaymentProcessorFactory {
  abstract createProcessor(): PaymentProcessor;
  
  processPayment(amount: number): boolean {
    const processor = this.createProcessor();
    return processor.process(amount);
  }
}

class CreditCardFactory extends PaymentProcessorFactory {
  createProcessor(): PaymentProcessor {
    return new CreditCardProcessor();
  }
}

class PayPalFactory extends PaymentProcessorFactory {
  createProcessor(): PaymentProcessor {
    return new PayPalProcessor();
  }
}

class CryptoFactory extends PaymentProcessorFactory {
  createProcessor(): PaymentProcessor {
    return new CryptoProcessor();
  }
}

// استفاده
const paymentType = "creditcard";
let factory: PaymentProcessorFactory;

switch (paymentType) {
  case "creditcard":
    factory = new CreditCardFactory();
    break;
  case "paypal":
    factory = new PayPalFactory();
    break;
  case "crypto":
    factory = new CryptoFactory();
    break;
  default:
    throw new Error("نوع پرداخت نامعتبر است");
}

factory.processPayment(100000);

۳. Abstract Factory (کارخانه انتزاعی)

// محصولات انتزاعی
interface Button {
  render(): void;
  onClick(): void;
}

interface Checkbox {
  render(): void;
  toggle(): void;
}

interface Dialog {
  show(): void;
  close(): void;
}

// محصولات مخصوص Windows
class WindowsButton implements Button {
  render(): void {
    console.log("رندر دکمه Windows");
  }
  
  onClick(): void {
    console.log("کلیک روی دکمه Windows");
  }
}

class WindowsCheckbox implements Checkbox {
  render(): void {
    console.log("رندر چک‌باکس Windows");
  }
  
  toggle(): void {
    console.log("تغییر وضعیت چک‌باکس Windows");
  }
}

class WindowsDialog implements Dialog {
  show(): void {
    console.log("نمایش دیالوگ Windows");
  }
  
  close(): void {
    console.log("بستن دیالوگ Windows");
  }
}

// محصولات مخصوص macOS
class MacButton implements Button {
  render(): void {
    console.log("رندر دکمه macOS");
  }
  
  onClick(): void {
    console.log("کلیک روی دکمه macOS");
  }
}

class MacCheckbox implements Checkbox {
  render(): void {
    console.log("رندر چک‌باکس macOS");
  }
  
  toggle(): void {
    console.log("تغییر وضعیت چک‌باکس macOS");
  }
}

class MacDialog implements Dialog {
  show(): void {
    console.log("نمایش دیالوگ macOS");
  }
  
  close(): void {
    console.log("بستن دیالوگ macOS");
  }
}

// کارخانه انتزاعی
interface GUIFactory {
  createButton(): Button;
  createCheckbox(): Checkbox;
  createDialog(): Dialog;
}

// کارخانه Windows
class WindowsFactory implements GUIFactory {
  createButton(): Button {
    return new WindowsButton();
  }
  
  createCheckbox(): Checkbox {
    return new WindowsCheckbox();
  }
  
  createDialog(): Dialog {
    return new WindowsDialog();
  }
}

// کارخانه macOS
class MacFactory implements GUIFactory {
  createButton(): Button {
    return new MacButton();
  }
  
  createCheckbox(): Checkbox {
    return new MacCheckbox();
  }
  
  createDialog(): Dialog {
    return new MacDialog();
  }
}

// کلاینت
class Application {
  private factory: GUIFactory;
  private button: Button;
  private checkbox: Checkbox;
  private dialog: Dialog;
  
  constructor(factory: GUIFactory) {
    this.factory = factory;
    this.button = factory.createButton();
    this.checkbox = factory.createCheckbox();
    this.dialog = factory.createDialog();
  }
  
  renderUI(): void {
    this.button.render();
    this.checkbox.render();
    this.dialog.show();
  }
}

// استفاده
const os = "windows"; // یا "mac"
let factory: GUIFactory;

if (os === "windows") {
  factory = new WindowsFactory();
} else if (os === "mac") {
  factory = new MacFactory();
} else {
  throw new Error("سیستم عامل نامعتبر");
}

const app = new Application(factory);
app.renderUI();

۴. Builder (سازنده)

class Computer {
  constructor(
    public cpu: string,
    public ram: string,
    public storage: string,
    public gpu?: string,
    public motherboard?: string,
    public powerSupply?: string,
    public coolingSystem?: string,
    public case?: string
  ) {}
  
  displaySpecs(): void {
    console.log("مشخصات کامپیوتر:");
    console.log(`CPU: ${this.cpu}`);
    console.log(`RAM: ${this.ram}`);
    console.log(`Storage: ${this.storage}`);
    if (this.gpu) console.log(`GPU: ${this.gpu}`);
    if (this.motherboard) console.log(`Motherboard: ${this.motherboard}`);
    if (this.powerSupply) console.log(`Power Supply: ${this.powerSupply}`);
    if (this.coolingSystem) console.log(`Cooling System: ${this.coolingSystem}`);
    if (this.case) console.log(`Case: ${this.case}`);
  }
}

interface ComputerBuilder {
  setCPU(cpu: string): this;
  setRAM(ram: string): this;
  setStorage(storage: string): this;
  setGPU(gpu: string): this;
  setMotherboard(motherboard: string): this;
  setPowerSupply(powerSupply: string): this;
  setCoolingSystem(coolingSystem: string): this;
  setCase(caseType: string): this;
  build(): Computer;
}

class GamingComputerBuilder implements ComputerBuilder {
  private cpu!: string;
  private ram!: string;
  private storage!: string;
  private gpu!: string;
  private motherboard!: string;
  private powerSupply!: string;
  private coolingSystem!: string;
  private case!: string;
  
  setCPU(cpu: string): this {
    this.cpu = cpu;
    return this;
  }
  
  setRAM(ram: string): this {
    this.ram = ram;
    return this;
  }
  
  setStorage(storage: string): this {
    this.storage = storage;
    return this;
  }
  
  setGPU(gpu: string): this {
    this.gpu = gpu;
    return this;
  }
  
  setMotherboard(motherboard: string): this {
    this.motherboard = motherboard;
    return this;
  }
  
  setPowerSupply(powerSupply: string): this {
    this.powerSupply = powerSupply;
    return this;
  }
  
  setCoolingSystem(coolingSystem: string): this {
    this.coolingSystem = coolingSystem;
    return this;
  }
  
  setCase(caseType: string): this {
    this.case = caseType;
    return this;
  }
  
  build(): Computer {
    return new Computer(
      this.cpu,
      this.ram,
      this.storage,
      this.gpu,
      this.motherboard,
      this.powerSupply,
      this.coolingSystem,
      this.case
    );
  }
}

class OfficeComputerBuilder implements ComputerBuilder {
  private cpu!: string;
  private ram!: string;
  private storage!: string;
  
  setCPU(cpu: string): this {
    this.cpu = cpu;
    return this;
  }
  
  setRAM(ram: string): this {
    this.ram = ram;
    return this;
  }
  
  setStorage(storage: string): this {
    this.storage = storage;
    return this;
  }
  
  setGPU(gpu: string): this { return this; } // نیازی نیست
  setMotherboard(motherboard: string): this { return this; }
  setPowerSupply(powerSupply: string): this { return this; }
  setCoolingSystem(coolingSystem: string): this { return this; }
  setCase(caseType: string): this { return this; }
  
  build(): Computer {
    return new Computer(this.cpu, this.ram, this.storage);
  }
}

// مدیر ساخت
class ComputerDirector {
  constructGamingComputer(builder: ComputerBuilder): Computer {
    return builder
      .setCPU("Intel Core i9-13900K")
      .setRAM("32GB DDR5")
      .setStorage("2TB NVMe SSD")
      .setGPU("NVIDIA RTX 4090")
      .setMotherboard("ASUS ROG Maximus Z790")
      .setPowerSupply("1200W 80+ Platinum")
      .setCoolingSystem("Liquid Cooling AIO")
      .setCase("Full Tower RGB")
      .build();
  }
  
  constructOfficeComputer(builder: ComputerBuilder): Computer {
    return builder
      .setCPU("Intel Core i5-13400")
      .setRAM("16GB DDR4")
      .setStorage("512GB SSD")
      .build();
  }
}

// استفاده
const director = new ComputerDirector();
const gamingBuilder = new GamingComputerBuilder();
const officeBuilder = new OfficeComputerBuilder();

const gamingPC = director.constructGamingComputer(gamingBuilder);
const officePC = director.constructOfficeComputer(officeBuilder);

gamingPC.displaySpecs();
officePC.displaySpecs();

الگوهای ساختاری (Structural Patterns)

۵. Adapter (سازگارکننده)

// سرویس قدیمی
class LegacyPaymentSystem {
  makePayment(amountInDollar: number, cardNumber: string): string {
    return `پرداخت $${amountInDollar} با کارت ${cardNumber} انجام شد`;
  }
}

// رابط جدید
interface ModernPaymentService {
  processPayment(amount: number, currency: string, paymentMethod: string): string;
}

// سرویس جدید
class NewPaymentService implements ModernPaymentService {
  processPayment(amount: number, currency: string, paymentMethod: string): string {
    return `پرداخت ${amount} ${currency} با ${paymentMethod} انجام شد`;
  }
}

// Adapter برای سازگاری سرویس قدیمی
class LegacyPaymentAdapter implements ModernPaymentService {
  private legacySystem: LegacyPaymentSystem;
  
  constructor(legacySystem: LegacyPaymentSystem) {
    this.legacySystem = legacySystem;
  }
  
  processPayment(amount: number, currency: string, paymentMethod: string): string {
    // تبدیل تومان به دلار (نرخ فرضی)
    const exchangeRate = 50000; // 1 دلار = 50000 تومان
    const amountInDollar = amount / exchangeRate;
    
    // استفاده از سرویس قدیمی
    return this.legacySystem.makePayment(amountInDollar, paymentMethod);
  }
}

// استفاده
const legacySystem = new LegacyPaymentSystem();
const newSystem = new NewPaymentService();
const adapter = new LegacyPaymentAdapter(legacySystem);

// همه با رابط یکسان کار می‌کنند
const paymentServices: ModernPaymentService[] = [newSystem, adapter];

paymentServices.forEach(service => {
  console.log(service.processPayment(100000, "تومان", "1234-5678-9012-3456"));
});

۶. Decorator (تزیین‌کننده)

// کامپوننت پایه
interface Notifier {
  send(message: string): void;
}

// کامپوننت اصلی
class EmailNotifier implements Notifier {
  send(message: string): void {
    console.log(`ارسال ایمیل: ${message}`);
  }
}

// Decorator پایه
abstract class NotifierDecorator implements Notifier {
  protected wrappee: Notifier;
  
  constructor(notifier: Notifier) {
    this.wrappee = notifier;
  }
  
  send(message: string): void {
    this.wrappee.send(message);
  }
}

// Decoratorهای خاص
class SMSDecorator extends NotifierDecorator {
  send(message: string): void {
    super.send(message);
    this.sendSMS(message);
  }
  
  private sendSMS(message: string): void {
    console.log(`ارسال SMS: ${message}`);
  }
}

class PushDecorator extends NotifierDecorator {
  send(message: string): void {
    super.send(message);
    this.sendPushNotification(message);
  }
  
  private sendPushNotification(message: string): void {
    console.log(`ارسال نوتیفیکیشن: ${message}`);
  }
}

class SlackDecorator extends NotifierDecorator {
  send(message: string): void {
    super.send(message);
    this.sendSlackMessage(message);
  }
  
  private sendSlackMessage(message: string): void {
    console.log(`ارسال پیام Slack: ${message}`);
  }
}

class EncryptionDecorator extends NotifierDecorator {
  send(message: string): void {
    const encryptedMessage = this.encrypt(message);
    super.send(encryptedMessage);
  }
  
  private encrypt(message: string): string {
    // الگوریتم رمزنگاری ساده
    return btoa(message); // Base64
  }
}

// استفاده
let notifier: Notifier = new EmailNotifier();

// اضافه کردن قابلیت‌ها
notifier = new SMSDecorator(notifier);
notifier = new PushDecorator(notifier);
notifier = new SlackDecorator(notifier);
notifier = new EncryptionDecorator(notifier);

notifier.send("پیام مهم برای کاربر");

۷. Facade (نما)

// سیستم‌های پیچیده
class InventorySystem {
  checkAvailability(productId: string, quantity: number): boolean {
    console.log(`بررسی موجودی محصول ${productId} به مقدار ${quantity}`);
    return true;
  }
  
  reserve(productId: string, quantity: number): void {
    console.log(`رزرو محصول ${productId} به مقدار ${quantity}`);
  }
  
  updateStock(productId: string, quantity: number): void {
    console.log(`به‌روزرسانی موجودی محصول ${productId} به مقدار ${quantity}`);
  }
}

class PaymentSystem {
  processPayment(orderId: string, amount: number, paymentMethod: string): boolean {
    console.log(`پرداخت سفارش ${orderId} به مبلغ ${amount} با روش ${paymentMethod}`);
    return true;
  }
  
  refund(orderId: string, amount: number): void {
    console.log(`عودت مبلغ ${amount} برای سفارش ${orderId}`);
  }
}

class ShippingSystem {
  calculateShipping(address: string, weight: number): number {
    console.log(`محاسبه هزینه ارسال به آدرس ${address} با وزن ${weight}`);
    return weight * 5000; // هزینه فرضی
  }
  
  scheduleDelivery(orderId: string, address: string): string {
    console.log(`زمان‌بندی ارسال سفارش ${orderId} به آدرس ${address}`);
    return "2024-12-10";
  }
  
  trackDelivery(orderId: string): string {
    console.log(`ردیابی سفارش ${orderId}`);
    return "در حال ارسال";
  }
}

class NotificationSystem {
  sendOrderConfirmation(orderId: string, email: string): void {
    console.log(`ارسال تاییدیه سفارش ${orderId} به ایمیل ${email}`);
  }
  
  sendShippingNotification(orderId: string, email: string, trackingNumber: string): void {
    console.log(`ارسال اطلاعیه ارسال سفارش ${orderId} به ایمیل ${email}`);
  }
}

// Facade - رابط ساده
class OrderFacade {
  private inventory: InventorySystem;
  private payment: PaymentSystem;
  private shipping: ShippingSystem;
  private notification: NotificationSystem;
  
  constructor() {
    this.inventory = new InventorySystem();
    this.payment = new PaymentSystem();
    this.shipping = new ShippingSystem();
    this.notification = new NotificationSystem();
  }
  
  placeOrder(
    productId: string,
    quantity: number,
    customerEmail: string,
    shippingAddress: string,
    paymentMethod: string,
    amount: number
  ): string {
    const orderId = `ORD-${Date.now()}`;
    
    console.log(`
=== شروع فرآیند سفارش ${orderId} ===`);
    
    // ۱. بررسی موجودی
    if (!this.inventory.checkAvailability(productId, quantity)) {
      throw new Error("محصول موجود نیست");
    }
    
    // ۲. رزرو محصول
    this.inventory.reserve(productId, quantity);
    
    // ۳. پرداخت
    if (!this.payment.processPayment(orderId, amount, paymentMethod)) {
      this.inventory.updateStock(productId, -quantity); // آزاد کردن رزرو
      throw new Error("پرداخت ناموفق بود");
    }
    
    // ۴. محاسبه هزینه ارسال
    const shippingCost = this.shipping.calculateShipping(shippingAddress, quantity);
    console.log(`هزینه ارسال: ${shippingCost} تومان`);
    
    // ۵. زمان‌بندی ارسال
    const deliveryDate = this.shipping.scheduleDelivery(orderId, shippingAddress);
    
    // ۶. ارسال نوتیفیکیشن
    this.notification.sendOrderConfirmation(orderId, customerEmail);
    
    // ۷. به‌روزرسانی موجودی
    this.inventory.updateStock(productId, quantity);
    
    console.log(`=== سفارش ${orderId} با موفقیت ثبت شد ===
`);
    
    return orderId;
  }
  
  trackOrder(orderId: string): string {
    return this.shipping.trackDelivery(orderId);
  }
  
  cancelOrder(
    orderId: string,
    productId: string,
    quantity: number,
    amount: number
  ): void {
    console.log(`
=== شروع فرآیند لغو سفارش ${orderId} ===`);
    
    // ۱. عودت وجه
    this.payment.refund(orderId, amount);
    
    // ۲. برگشت موجودی
    this.inventory.updateStock(productId, -quantity);
    
    console.log(`=== سفارش ${orderId} با موفقیت لغو شد ===
`);
  }
}

// استفاده ساده توسط کلاینت
const orderSystem = new OrderFacade();

try {
  const orderId = orderSystem.placeOrder(
    "PROD-123",
    2,
    "customer@example.com",
    "تهران، خیابان ولیعصر",
    "کارت اعتباری",
    200000
  );
  
  console.log(`شماره پیگیری سفارش: ${orderId}`);
  
  const status = orderSystem.trackOrder(orderId);
  console.log(`وضعیت سفارش: ${status}`);
  
} catch (error) {
  console.error(`خطا در ثبت سفارش: ${error.message}`);
}

۸. Proxy (پراکسی)

// موضوع اصلی
interface VideoDownloader {
  download(videoId: string): string;
}

// پیاده‌سازی واقعی
class RealVideoDownloader implements VideoDownloader {
  download(videoId: string): string {
    console.log(`دانلود ویدیو ${videoId} از سرور...`);
    // شبیه‌سازی زمان‌بر بودن دانلود
    this.simulateHeavyOperation();
    return `محتوای ویدیو ${videoId}`;
  }
  
  private simulateHeavyOperation(): void {
    // شبیه‌سازی عملیات سنگین
    for (let i = 0; i < 1000000000; i++) {
      // عملیات سنگین
    }
  }
}

// Proxy با کش
class CachedVideoDownloader implements VideoDownloader {
  private realDownloader: RealVideoDownloader;
  private cache: Map;
  
  constructor() {
    this.realDownloader = new RealVideoDownloader();
    this.cache = new Map();
  }
  
  download(videoId: string): string {
    // بررسی کش
    if (this.cache.has(videoId)) {
      console.log(`دریافت ویدیو ${videoId} از کش`);
      return this.cache.get(videoId)!;
    }
    
    // دانلود واقعی
    console.log(`ویدیو ${videoId} در کش یافت نشد. در حال دانلود...`);
    const videoContent = this.realDownloader.download(videoId);
    
    // ذخیره در کش
    this.cache.set(videoId, videoContent);
    console.log(`ویدیو ${videoId} در کش ذخیره شد`);
    
    return videoContent;
  }
  
  clearCache(): void {
    console.log("پاک کردن کش");
    this.cache.clear();
  }
  
  getCacheSize(): number {
    return this.cache.size;
  }
}

// Proxy با کنترل دسترسی
interface SensitiveData {
  getData(userRole: string): string;
}

class RealSensitiveData implements SensitiveData {
  getData(userRole: string): string {
    return "داده‌های محرمانه سیستم";
  }
}

class ProtectedSensitiveData implements SensitiveData {
  private realData: RealSensitiveData;
  
  constructor() {
    this.realData = new RealSensitiveData();
  }
  
  getData(userRole: string): string {
    // کنترل دسترسی
    if (userRole !== "admin") {
      throw new Error("دسترسی غیرمجاز. فقط ادمین‌ها می‌توانند به این داده‌ها دسترسی داشته باشند");
    }
    
    // لاگ‌گیری
    console.log(`کاربر با نقش ${userRole} درخواست داده‌های محرمانه کرد`);
    
    return this.realData.getData(userRole);
  }
}

// استفاده
const downloader = new CachedVideoDownloader();

// اولین بار دانلود واقعی
console.log(downloader.download("video-123"));
console.log(`اندازه کش: ${downloader.getCacheSize()}`);

// بار دوم از کش
console.log(downloader.download("video-123"));
console.log(`اندازه کش: ${downloader.getCacheSize()}`);

// داده جدید
console.log(downloader.download("video-456"));
console.log(`اندازه کش: ${downloader.getCacheSize()}`);

// کنترل دسترسی
const dataAccess = new ProtectedSensitiveData();

try {
  console.log(dataAccess.getData("user")); // خطا می‌دهد
} catch (error) {
  console.error(error.message);
}

console.log(dataAccess.getData("admin")); // موفق

الگوهای رفتاری (Behavioral Patterns)

۹. Observer (ناظر)

// رابط ناظر
interface Observer {
  update(temperature: number, humidity: number, pressure: number): void;
}

// رابط موضوع
interface Subject {
  registerObserver(observer: Observer): void;
  removeObserver(observer: Observer): void;
  notifyObservers(): void;
}

// موضوع اصلی
class WeatherStation implements Subject {
  private observers: Observer[] = [];
  private temperature: number = 0;
  private humidity: number = 0;
  private pressure: number = 0;
  
  registerObserver(observer: Observer): void {
    this.observers.push(observer);
  }
  
  removeObserver(observer: Observer): void {
    const index = this.observers.indexOf(observer);
    if (index !== -1) {
      this.observers.splice(index, 1);
    }
  }
  
  notifyObservers(): void {
    for (const observer of this.observers) {
      observer.update(this.temperature, this.humidity, this.pressure);
    }
  }
  
  setMeasurements(temperature: number, humidity: number, pressure: number): void {
    this.temperature = temperature;
    this.humidity = humidity;
    this.pressure = pressure;
    this.measurementsChanged();
  }
  
  private measurementsChanged(): void {
    this.notifyObservers();
  }
}

// ناظرها
class CurrentConditionsDisplay implements Observer {
  private temperature: number = 0;
  private humidity: number = 0;
  
  update(temperature: number, humidity: number, pressure: number): void {
    this.temperature = temperature;
    this.humidity = humidity;
    this.display();
  }
  
  display(): void {
    console.log(`شرایط کنونی: دما ${this.temperature}°C، رطوبت ${this.humidity}%`);
  }
}

class StatisticsDisplay implements Observer {
  private temperatures: number[] = [];
  private humidities: number[] = [];
  private pressures: number[] = [];
  
  update(temperature: number, humidity: number, pressure: number): void {
    this.temperatures.push(temperature);
    this.humidities.push(humidity);
    this.pressures.push(pressure);
    this.display();
  }
  
  display(): void {
    const avgTemp = this.calculateAverage(this.temperatures);
    const maxTemp = Math.max(...this.temperatures);
    const minTemp = Math.min(...this.temperatures);
    
    console.log(`آمار: میانگین دما ${avgTemp.toFixed(1)}°C، حداقل ${minTemp}°C، حداکثر ${maxTemp}°C`);
  }
  
  private calculateAverage(numbers: number[]): number {
    if (numbers.length === 0) return 0;
    const sum = numbers.reduce((a, b) => a + b, 0);
    return sum / numbers.length;
  }
}

class ForecastDisplay implements Observer {
  private lastPressure: number = 0;
  private currentPressure: number = 0;
  
  update(temperature: number, humidity: number, pressure: number): void {
    this.lastPressure = this.currentPressure;
    this.currentPressure = pressure;
    this.display();
  }
  
  display(): void {
    if (this.currentPressure > this.lastPressure) {
      console.log("پیش‌بینی: آب و هوا در حال بهبود است");
    } else if (this.currentPressure === this.lastPressure) {
      console.log("پیش‌بینی: آب و هوا تغییری نمی‌کند");
    } else {
      console.log("پیش‌بینی: باران در راه است");
    }
  }
}

// استفاده
const weatherStation = new WeatherStation();

const currentDisplay = new CurrentConditionsDisplay();
const statisticsDisplay = new StatisticsDisplay();
const forecastDisplay = new ForecastDisplay();

// ثبت ناظرها
weatherStation.registerObserver(currentDisplay);
weatherStation.registerObserver(statisticsDisplay);
weatherStation.registerObserver(forecastDisplay);

// تغییر شرایط آب و هوا
console.log("=== تغییر اول ===");
weatherStation.setMeasurements(25, 65, 1013);

console.log("
=== تغییر دوم ===");
weatherStation.setMeasurements(27, 70, 1010);

console.log("
=== تغییر سوم ===");
weatherStation.setMeasurements(22, 90, 1005);

// حذف یک ناظر
console.log("
=== حذف ناظر آمار ===");
weatherStation.removeObserver(statisticsDisplay);

console.log("
=== تغییر چهارم ===");
weatherStation.setMeasurements(20, 95, 1002);

۱۰. Strategy (استراتژی)

// استراتژی پایه
interface CompressionStrategy {
  compress(file: string): string;
}

// استراتژی‌های مختلف
class ZipCompression implements CompressionStrategy {
  compress(file: string): string {
    console.log(`فشرده‌سازی ${file} با فرمت ZIP`);
    return `${file}.zip`;
  }
}

class RarCompression implements CompressionStrategy {
  compress(file: string): string {
    console.log(`فشرده‌سازی ${file} با فرمت RAR`);
    return `${file}.rar`;
  }
}

class GzipCompression implements CompressionStrategy {
  compress(file: string): string {
    console.log(`فشرده‌سازی ${file} با فرمت GZIP`);
    return `${file}.gz`;
  }
}

class SevenZipCompression implements CompressionStrategy {
  compress(file: string): string {
    console.log(`فشرده‌سازی ${file} با فرمت 7Z`);
    return `${file}.7z`;
  }
}

// کلاس زمینه (Context)
class FileCompressor {
  private strategy: CompressionStrategy;
  
  constructor(strategy: CompressionStrategy) {
    this.strategy = strategy;
  }
  
  setStrategy(strategy: CompressionStrategy): void {
    this.strategy = strategy;
  }
  
  compressFile(file: string): string {
    return this.strategy.compress(file);
  }
  
  compressFiles(files: string[]): string[] {
    return files.map(file => this.compressFile(file));
  }
}

// استراتژی‌های مرتبه‌بندی
interface SortingStrategy {
  sort(items: number[]): number[];
}

class BubbleSort implements SortingStrategy {
  sort(items: number[]): number[] {
    console.log("مرتب‌سازی با روش Bubble Sort");
    const arr = [...items];
    const n = arr.length;
    
    for (let i = 0; i < n - 1; i++) {
      for (let j = 0; j < n - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
          [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        }
      }
    }
    
    return arr;
  }
}

class QuickSort implements SortingStrategy {
  sort(items: number[]): number[] {
    console.log("مرتب‌سازی با روش Quick Sort");
    return this.quickSort([...items], 0, items.length - 1);
  }
  
  private quickSort(arr: number[], low: number, high: number): number[] {
    if (low < high) {
      const pi = this.partition(arr, low, high);
      this.quickSort(arr, low, pi - 1);
      this.quickSort(arr, pi + 1, high);
    }
    return arr;
  }
  
  private partition(arr: number[], low: number, high: number): number {
    const pivot = arr[high];
    let i = low - 1;
    
    for (let j = low; j < high; j++) {
      if (arr[j] < pivot) {
        i++;
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
    }
    
    [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
    return i + 1;
  }
}

class MergeSort implements SortingStrategy {
  sort(items: number[]): number[] {
    console.log("مرتب‌سازی با روش Merge Sort");
    return this.mergeSort([...items]);
  }
  
  private mergeSort(arr: number[]): number[] {
    if (arr.length <= 1) {
      return arr;
    }
    
    const mid = Math.floor(arr.length / 2);
    const left = this.mergeSort(arr.slice(0, mid));
    const right = this.mergeSort(arr.slice(mid));
    
    return this.merge(left, right);
  }
  
  private merge(left: number[], right: number[]): number[] {
    const result: number[] = [];
    let i = 0, j = 0;
    
    while (i < left.length && j < right.length) {
      if (left[i] < right[j]) {
        result.push(left[i]);
        i++;
      } else {
        result.push(right[j]);
        j++;
      }
    }
    
    return result.concat(left.slice(i)).concat(right.slice(j));
  }
}

// مرتب‌ساز پویا
class DynamicSorter {
  private strategy: SortingStrategy;
  
  constructor(strategy: SortingStrategy) {
    this.strategy = strategy;
  }
  
  setStrategy(strategy: SortingStrategy): void {
    this.strategy = strategy;
  }
  
  sort(items: number[]): number[] {
    return this.strategy.sort(items);
  }
}

// استفاده
const files = ["document.txt", "image.jpg", "data.csv"];
const numbers = [64, 34, 25, 12, 22, 11, 90];

// فشرده‌سازی
console.log("=== فشرده‌سازی فایل‌ها ===");
const compressor = new FileCompressor(new ZipCompression());
console.log(compressor.compressFiles(files));

compressor.setStrategy(new RarCompression());
console.log(compressor.compressFiles(files));

compressor.setStrategy(new GzipCompression());
console.log(compressor.compressFiles(files));

// مرتب‌سازی
console.log("
=== مرتب‌سازی اعداد ===");
const sorter = new DynamicSorter(new BubbleSort());
console.log("مرتب شده:", sorter.sort(numbers));

sorter.setStrategy(new QuickSort());
console.log("مرتب شده:", sorter.sort(numbers));

sorter.setStrategy(new MergeSort());
console.log("مرتب شده:", sorter.sort(numbers));

الگوهای معماری (Architectural Patterns)

۱. لایه‌ای (Layered Architecture)

// لایه Presentation (نمایش)
class UserController {
  constructor(private userService: UserService) {}
  
  async createUser(req: Request, res: Response): Promise {
    try {
      const userData = req.body;
      const user = await this.userService.createUser(userData);
      res.status(201).json(user);
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  }
}

// لایه Business Logic (منطق کسب‌وکار)
class UserService {
  constructor(
    private userRepository: UserRepository,
    private emailService: EmailService,
    private validator: UserValidator
  ) {}
  
  async createUser(userData: CreateUserDto): Promise {
    // اعتبارسنجی
    await this.validator.validate(userData);
    
    // ایجاد کاربر
    const user = await this.userRepository.create(userData);
    
    // ارسال ایمیل خوش‌آمدگویی
    await this.emailService.sendWelcomeEmail(user.email, user.name);
    
    // لاگ‌گیری
    console.log(`کاربر جدید ایجاد شد: ${user.email}`);
    
    return user;
  }
}

// لایه Data Access (دسترسی به داده)
class UserRepository {
  constructor(private database: Database) {}
  
  async create(userData: CreateUserDto): Promise {
    const query = `
      INSERT INTO users (name, email, password)
      VALUES ($1, $2, $3)
      RETURNING *`;
    
    const result = await this.database.query(query, [
      userData.name,
      userData.email,
      userData.password
    ]);
    
    return result.rows[0];
  }
  
  async findById(id: number): Promise {
    const query = `SELECT * FROM users WHERE id = $1`;
    const result = await this.database.query(query, [id]);
    return result.rows[0] || null;
  }
}

// لایه Infrastructure (زیرساخت)
class Database {
  async query(sql: string, params: any[] = []): Promise {
    // پیاده‌سازی اتصال به دیتابیس
    return { rows: [] };
  }
}

class EmailService {
  async sendWelcomeEmail(to: string, name: string): Promise {
    // پیاده‌سازی ارسال ایمیل
    console.log(`ایمیل خوش‌آمدگویی به ${to} ارسال شد`);
  }
}

۲. Clean Architecture

// لایه Entities (موجودیت‌ها)
class User {
  constructor(
    public id: number,
    public name: string,
    public email: string,
    public password: string,
    public createdAt: Date
  ) {}
  
  validate(): void {
    if (!this.email.includes("@")) {
      throw new Error("ایمیل نامعتبر است");
    }
    if (this.password.length < 8) {
      throw new Error("رمز عبور باید حداقل ۸ کاراکتر باشد");
    }
  }
  
  toJSON(): any {
    return {
      id: this.id,
      name: this.name,
      email: this.email,
      createdAt: this.createdAt
    };
  }
}

// لایه Use Cases (موارد استفاده)
interface UserRepository {
  save(user: User): Promise;
  findById(id: number): Promise;
  findByEmail(email: string): Promise;
}

class CreateUserUseCase {
  constructor(private userRepository: UserRepository) {}
  
  async execute(input: CreateUserInput): Promise {
    // اعتبارسنجی
    if (!input.name || !input.email || !input.password) {
      throw new Error("تمام فیلدها الزامی هستند");
    }
    
    // بررسی تکراری نبودن ایمیل
    const existingUser = await this.userRepository.findByEmail(input.email);
    if (existingUser) {
      throw new Error("ایمیل قبلاً ثبت شده است");
    }
    
    // ایجاد موجودیت
    const user = new User(
      0, // ID موقت
      input.name,
      input.email,
      await this.hashPassword(input.password),
      new Date()
    );
    
    // اعتبارسنجی موجودیت
    user.validate();
    
    // ذخیره
    const savedUser = await this.userRepository.save(user);
    
    return {
      id: savedUser.id,
      name: savedUser.name,
      email: savedUser.email,
      createdAt: savedUser.createdAt
    };
  }
  
  private async hashPassword(password: string): Promise {
    // الگوریتم هش
    return Buffer.from(password).toString("base64");
  }
}

// لایه Interface Adapters (سازگارکننده رابط)
class UserController {
  constructor(private createUserUseCase: CreateUserUseCase) {}
  
  async create(req: Request, res: Response): Promise {
    try {
      const input: CreateUserInput = req.body;
      const output = await this.createUserUseCase.execute(input);
      res.status(201).json(output);
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  }
}

// لایه Frameworks & Drivers (چارچوب‌ها و درایورها)
class PostgresUserRepository implements UserRepository {
  constructor(private connection: any) {}
  
  async save(user: User): Promise {
    const query = `
      INSERT INTO users (name, email, password, created_at)
      VALUES ($1, $2, $3, $4)
      RETURNING id, name, email, password, created_at`;
    
    const result = await this.connection.query(query, [
      user.name,
      user.email,
      user.password,
      user.createdAt
    ]);
    
    const row = result.rows[0];
    return new User(
      row.id,
      row.name,
      row.email,
      row.password,
      row.created_at
    );
  }
  
  async findById(id: number): Promise {
    const query = `SELECT * FROM users WHERE id = $1`;
    const result = await this.connection.query(query, [id]);
    
    if (result.rows.length === 0) {
      return null;
    }
    
    const row = result.rows[0];
    return new User(
      row.id,
      row.name,
      row.email,
      row.password,
      row.created_at
    );
  }
  
  async findByEmail(email: string): Promise {
    const query = `SELECT * FROM users WHERE email = $1`;
    const result = await this.connection.query(query, [email]);
    
    if (result.rows.length === 0) {
      return null;
    }
    
    const row = result.rows[0];
    return new User(
      row.id,
      row.name,
      row.email,
      row.password,
      row.created_at
    );
  }
}

۳. میکروسرویس (Microservices)

// سرویس کاربران
class UserService {
  private users: Map = new Map();
  
  async createUser(data: CreateUserRequest): Promise {
    const id = Date.now();
    const user: User = {
      id,
      name: data.name,
      email: data.email,
      createdAt: new Date()
    };
    
    this.users.set(id, user);
    
    // انتشار رویداد
    await this.publishEvent("UserCreated", {
      userId: id,
      email: data.email,
      timestamp: new Date()
    });
    
    return user;
  }
  
  async getUser(id: number): Promise {
    return this.users.get(id) || null;
  }
  
  private async publishEvent(eventType: string, data: any): Promise {
    // پیاده‌سازی انتشار رویداد
    console.log(`رویداد ${eventType}:`, data);
  }
}

// سرویس سفارشات
class OrderService {
  private orders: Map = new Map();
  
  async createOrder(data: CreateOrderRequest): Promise {
    // تایید کاربر
    const user = await this.verifyUser(data.userId);
    
    const id = Date.now();
    const order: Order = {
      id,
      userId: data.userId,
      items: data.items,
      total: this.calculateTotal(data.items),
      status: "pending",
      createdAt: new Date()
    };
    
    this.orders.set(id, order);
    
    // انتشار رویداد
    await this.publishEvent("OrderCreated", {
      orderId: id,
      userId: data.userId,
      total: order.total,
      timestamp: new Date()
    });
    
    // استاک کاهش یابد (ارتباط ناهمگام)
    await this.updateInventory(data.items);
    
    return order;
  }
  
  private async verifyUser(userId: number): Promise {
    // تماس با سرویس کاربران
    const response = await fetch(`http://user-service/users/${userId}`);
    if (!response.ok) {
      throw new Error("کاربر یافت نشد");
    }
    return await response.json();
  }
  
  private calculateTotal(items: OrderItem[]): number {
    return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
  }
  
  private async updateInventory(items: OrderItem[]): Promise {
    for (const item of items) {
      // تماس ناهمگام با سرویس انبار
      await this.sendMessage("InventoryService", {
        type: "ReduceStock",
        productId: item.productId,
        quantity: item.quantity
      });
    }
  }
  
  private async sendMessage(service: string, message: any): Promise {
    // پیاده‌سازی پیام‌رسانی
    console.log(`ارسال پیام به ${service}:`, message);
  }
  
  private async publishEvent(eventType: string, data: any): Promise {
    // پیاده‌سازی انتشار رویداد
    console.log(`رویداد ${eventType}:`, data);
  }
}

// API Gateway
class ApiGateway {
  private routes: Map = new Map([
    ["/users", "http://user-service:3001"],
    ["/orders", "http://order-service:3002"],
    ["/products", "http://product-service:3003"],
    ["/inventory", "http://inventory-service:3004"]
  ]);
  
  async handleRequest(req: Request): Promise {
    const url = new URL(req.url);
    const path = url.pathname;
    
    // یافتن سرویس مقصد
    let targetService: string | undefined;
    for (const [route, service] of this.routes) {
      if (path.startsWith(route)) {
        targetService = service;
        break;
      }
    }
    
    if (!targetService) {
      return new Response("مسیر یافت نشد", { status: 404 });
    }
    
    // اعتبارسنجی JWT
    const authHeader = req.headers.get("Authorization");
    if (!authHeader) {
      return new Response("دسترسی غیرمجاز", { status: 401 });
    }
    
    // اعتبارسنجی در سرویس Auth
    const isValid = await this.validateToken(authHeader);
    if (!isValid) {
      return new Response("توکن نامعتبر", { status: 401 });
    }
    
    // روتینگ به سرویس مقصد
    const targetUrl = `${targetService}${url.pathname}${url.search}`;
    const forwardedReq = new Request(targetUrl, {
      method: req.method,
      headers: req.headers,
      body: req.body
    });
    
    // لاگ‌گیری
    await this.logRequest(req, targetService);
    
    // ارسال درخواست
    return await fetch(forwardedReq);
  }
  
  private async validateToken(token: string): Promise {
    // پیاده‌سازی اعتبارسنجی JWT
    return token.startsWith("Bearer ");
  }
  
  private async logRequest(req: Request, targetService: string): Promise {
    console.log(`${req.method} ${req.url} -> ${targetService}`);
  }
}

۴. رویداد-محور (Event-Driven)

// سیستم پیام‌رسانی
interface Event {
  type: string;
  data: any;
  timestamp: Date;
  source: string;
}

interface EventHandler {
  handle(event: Event): Promise;
}

interface EventBus {
  publish(event: Event): Promise;
  subscribe(eventType: string, handler: EventHandler): void;
  unsubscribe(eventType: string, handler: EventHandler): void;
}

// پیاده‌سازی EventBus
class SimpleEventBus implements EventBus {
  private handlers: Map = new Map();
  
  async publish(event: Event): Promise {
    console.log(`انتشار رویداد: ${event.type}`, event.data);
    
    const handlers = this.handlers.get(event.type) || [];
    
    // اجرای همزمان همه هندلرها
    await Promise.all(
      handlers.map(handler => handler.handle(event))
    );
  }
  
  subscribe(eventType: string, handler: EventHandler): void {
    if (!this.handlers.has(eventType)) {
      this.handlers.set(eventType, []);
    }
    this.handlers.get(eventType)!.push(handler);
    console.log(`هندلر برای ${eventType} ثبت شد`);
  }
  
  unsubscribe(eventType: string, handler: EventHandler): void {
    const handlers = this.handlers.get(eventType);
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index !== -1) {
        handlers.splice(index, 1);
        console.log(`هندلر از ${eventType} حذف شد`);
      }
    }
  }
}

// رویدادها
class UserCreatedEvent implements Event {
  type = "UserCreated";
  
  constructor(
    public data: { userId: number; email: string; name: string },
    public timestamp: Date = new Date(),
    public source: string = "UserService"
  ) {}
}

class OrderPlacedEvent implements Event {
  type = "OrderPlaced";
  
  constructor(
    public data: { orderId: number; userId: number; total: number; items: any[] },
    public timestamp: Date = new Date(),
    public source: string = "OrderService"
  ) {}
}

class PaymentProcessedEvent implements Event {
  type = "PaymentProcessed";
  
  constructor(
    public data: { paymentId: number; orderId: number; amount: number; status: string },
    public timestamp: Date = new Date(),
    public source: string = "PaymentService"
  ) {}
}

// هندلرها
class EmailNotificationHandler implements EventHandler {
  async handle(event: Event): Promise {
    switch (event.type) {
      case "UserCreated":
        const userData = event.data as { email: string; name: string };
        await this.sendWelcomeEmail(userData.email, userData.name);
        break;
        
      case "OrderPlaced":
        const orderData = event.data as { userId: number; orderId: number; total: number };
        await this.sendOrderConfirmation(orderData.userId, orderData.orderId, orderData.total);
        break;
        
      case "PaymentProcessed":
        const paymentData = event.data as { orderId: number; amount: number; status: string };
        if (paymentData.status === "completed") {
          await this.sendPaymentReceipt(paymentData.orderId, paymentData.amount);
        }
        break;
    }
  }
  
  private async sendWelcomeEmail(email: string, name: string): Promise {
    console.log(`ارسال ایمیل خوش‌آمدگویی به ${email} با نام ${name}`);
    // پیاده‌سازی ارسال ایمیل
  }
  
  private async sendOrderConfirmation(userId: number, orderId: number, total: number): Promise {
    console.log(`ارسال تاییدیه سفارش ${orderId} به کاربر ${userId} با مبلغ ${total}`);
    // پیاده‌سازی ارسال ایمیل
  }
  
  private async sendPaymentReceipt(orderId: number, amount: number): Promise {
    console.log(`ارسال رسید پرداخت سفارش ${orderId} با مبلغ ${amount}`);
    // پیاده‌سازی ارسال ایمیل
  }
}

class AnalyticsHandler implements EventHandler {
  private metrics: Map = new Map();
  
  async handle(event: Event): Promise {
    // به‌روزرسانی متریک‌ها
    this.updateMetrics(event.type, event.data);
    
    // ذخیره رویداد برای تحلیل
    await this.storeEvent(event);
    
    // تولید گزارش
    if (this.shouldGenerateReport()) {
      await this.generateReport();
    }
  }
  
  private updateMetrics(eventType: string, data: any): void {
    const count = this.metrics.get(eventType) || 0;
    this.metrics.set(eventType, count + 1);
    
    console.log(`متریک ${eventType}: ${count + 1}`);
  }
  
  private async storeEvent(event: Event): Promise {
    // ذخیره در دیتابیس یا سیستم ذخیره‌سازی رویدادها
    console.log(`ذخیره رویداد ${event.type} برای تحلیل`);
  }
  
  private shouldGenerateReport(): boolean {
    // منطق زمان‌بندی گزارش
    return this.metrics.size % 10 === 0;
  }
  
  private async generateReport(): Promise {
    console.log("=== گزارش تحلیل رویدادها ===");
    for (const [eventType, count] of this.metrics) {
      console.log(`${eventType}: ${count} رویداد`);
    }
    console.log("==========================
");
  }
}

class InventoryHandler implements EventHandler {
  async handle(event: Event): Promise {
    if (event.type === "OrderPlaced") {
      const data = event.data as { items: any[] };
      await this.updateStock(data.items);
    }
  }
  
  private async updateStock(items: any[]): Promise {
    for (const item of items) {
      console.log(`کاهش موجودی محصول ${item.productId} به مقدار ${item.quantity}`);
      // پیاده‌سازی به‌روزرسانی موجودی
    }
  }
}

// استفاده
const eventBus = new SimpleEventBus();

// ثبت هندلرها
const emailHandler = new EmailNotificationHandler();
const analyticsHandler = new AnalyticsHandler();
const inventoryHandler = new InventoryHandler();

eventBus.subscribe("UserCreated", emailHandler);
eventBus.subscribe("UserCreated", analyticsHandler);
eventBus.subscribe("OrderPlaced", emailHandler);
eventBus.subscribe("OrderPlaced", analyticsHandler);
eventBus.subscribe("OrderPlaced", inventoryHandler);
eventBus.subscribe("PaymentProcessed", emailHandler);
eventBus.subscribe("PaymentProcessed", analyticsHandler);

// شبیه‌سازی جریان رویدادها
console.log("=== شبیه‌سازی سیستم رویداد-محور ===
");

// رویداد ۱: ایجاد کاربر
console.log("۱. کاربر جدید ایجاد شد");
await eventBus.publish(new UserCreatedEvent({
  userId: 1,
  email: "user@example.com",
  name: "علی رضایی"
}));

// رویداد ۲: سفارش جدید
console.log("
۲. سفارش جدید ثبت شد");
await eventBus.publish(new OrderPlacedEvent({
  orderId: 1001,
  userId: 1,
  total: 150000,
  items: [
    { productId: 101, name: "لپ‌تاپ", quantity: 1, price: 150000 }
  ]
}));

// رویداد ۳: پرداخت موفق
console.log("
۳. پرداخت انجام شد");
await eventBus.publish(new PaymentProcessedEvent({
  paymentId: 5001,
  orderId: 1001,
  amount: 150000,
  status: "completed"
}));

console.log("
=== شبیه‌سازی کامل شد ===");

نتیجه‌گیری

معماری نرم‌افزار و الگوهای طراحی ابزارهای قدرتمندی هستند که به توسعه‌دهندگان کمک می‌کنند سیستم‌های قابل نگهداری، مقیاس‌پذیر و قابل اطمینان بسازند. انتخاب الگوی مناسب به عوامل مختلفی مانند اندازه پروژه، پیچیدگی دامنه، تیم توسعه و نیازمندی‌های عملکردی بستگی دارد.

نکات کلیدی برای انتخاب الگوهای مناسب:

  1. اصل KISS: ابتدا ساده‌ترین راه‌حل را در نظر بگیرید
  2. اصل YAGNI: چیزی را پیاده‌سازی نکنید که فعلاً به آن نیاز ندارید
  3. قابل تست بودن: معماری باید تست‌پذیری را تسهیل کند
  4. قابل توسعه بودن: امکان اضافه کردن ویژگی‌های جدید بدون شکستن کد موجود
  5. قابل درک بودن: معماری باید برای همه اعضای تیم قابل فهم باشد

به یاد داشته باشید که هیچ معماری "بهترین" وجود ندارد. بهترین معماری معماری‌ای است که به بهترین وجه نیازهای پروژه شما را برآورده کند و با بلوغ تیم و محصول، تکامل یابد.