Behavioral Patterns: Template Method, Chain of Responsibility, State, Command, Observer, Strategy, Iterator, Mediator, Memento, Visitor
"Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects." — refactoring.guru، Behavioral Design Patterns
خلاصه (Summary): الگوهای رفتاری (Behavioral Patterns) به این سؤال جواب میدهند که «چه کسی چه کاری میکند و چه کسی به چه کسی خبر میدهد»: یک الگوریتم چطور به قطعههای قابلتعویض شکسته شود، یک درخواست چطور به کدی برسد که آن را رسیدگی میکند، و objectها چطور به هم واکنش نشان دهند بدون اینکه همدیگر را بشناسند. تمرکز (Focus): ده الگوی عنوان بهعلاوهٔ Interpreter؛ برای هر کدام هدف (Intent)، نمودار ساختار، اجزا، پیادهسازی idiomatic در Go (تابع، interface، channel، iter.Seq، go/ast) و Laravel 13 (Pipeline، middleware، event، job، enum، LazyCollection، tagged binding)، پیامدها، اشتباهگرفتنها، شکل توزیعشده و تست. هدف یادگیری (Learning goal): تشخیص دهید کدامیک از این یازده مسئله را دارید، الگوی مناسب (یا یک تابع ساده) را انتخاب کنید، آن را در Go و Laravel درست پیاده و تست کنید، و بدانید وقتی کد به سرویسها شکسته شد همان الگو چه شکلی پیدا میکند.
این صفحه مرجع کامل یازده الگوی رفتاری کاتالوگ Gang of Four است. ریشهٔ الگوها و سه خانوادهٔ آنها در Design Patterns: Introduction آمده؛ ساختن object در Creational Patterns؛ پوشاندن و ترکیب objectها (Decorator، Composite، Proxy، Facade) در Structural Patterns؛ و ترکیب الگوها در سیستم واقعی و سوءاستفاده از آنها در Patterns in Practice. حلقهٔ رویداد و callback بهعنوان یک مسئلهٔ طراحی در Control Flow & Event Handling است. چند الگوی این صفحه سازوکار پشت SOLID هستند: Strategy و Observer ابزار معمول Open–Closed هستند و Command و Mediator راه نگهداشتن Single Responsibility و Dependency Inversion وقتی کد بزرگ میشود.
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| هر یازده الگو در دو جدول | همهچیز در یک دقیقه |
| چرا این الگوها وجود دارند و چه هزینهای دارند | چرا الگوهای رفتاری |
| GoF ۱۹۹۴، refactoring.guru، iteratorهای Go 1.23، eventهای Laravel | از کجا آمده |
| Template Method، Chain of Responsibility، State، Command، Observer | الگوها، یکییکی |
| Strategy، Iterator، Mediator، Memento، Visitor، Interpreter | از Strategy تا Interpreter |
| کدام قابلیت stdlib یا فریمورک خودش همان الگوست | نگاه هر زبان |
| double dispatch، push و pull، sync و queued، پشتهٔ undo، جدول transition | سازوکار |
| تست هر الگو | تست هر الگو |
| workflow سفارش، زنجیرهٔ تأیید، undo/redo، audit log، ماژولهای event-driven | حل مسئلههای کلاسیک |
| Strategy و State و Template Method؛ Observer و pub/sub و Mediator؛ Command و Job و Transaction Script | انتخاب |
| Observer به broker، Command به صف، State به saga تبدیل میشود | در معماری |
| state machine سفارش + checkout با pipeline + observer، در Go و Laravel، با تست | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، همهٔ اصطلاحها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
یازده الگو. هر سطر در بخش الگوها باز میشود.
| الگو | به زبان ساده | مثال کوچک | idiom در Go | idiom در Laravel |
|---|---|---|---|---|
| Template Method | دستور پخت ثابت، مرحلههای قابلتعویض | خروجی: header، سطرها، footer | تابعی که interface Steps میگیرد | abstract class با متد final |
| Chain of Responsibility | درخواست را دستبهدست کن تا کسی رسیدگی یا متوقفش کند | Auth → log → rate limit → controller | func(http.Handler) http.Handler | middleware، Pipeline::send()->through() |
| State | object در هر وضعیت رفتار متفاوتی دارد و بین وضعیتها جابهجا میشود | سفارش: pending → paid → shipped | interface وضعیت یا جدول transition | enum با transitions() |
| Command | درخواست تبدیل به object | «پرداخت سفارش ۴۲ را capture کن» | مقدار با Do/Undo یا closure | Job صفشده، Bus::chain |
| Observer | به همهٔ مشترکها بگو چه شد | سفارش پرداخت شد → ایمیل، انبار | callback یا channel | event + listener، Eloquent observer |
| Strategy | یک الگوریتم را پشت یک interface با دیگری عوض کن | هزینهٔ ارسال ثابت یا وزنی | مقدار func؛ slices.SortFunc | interface + binding یا tag در container |
| Iterator | پیمایش مجموعه بدون دانستن نحوهٔ ذخیره | range روی درخت دستهبندی | iter.Seq، iter.Seq2، iter.Pull | generator، IteratorAggregate، LazyCollection |
| Mediator | اجزا فقط با یک هاب حرف میزنند | فرم checkout خلاصه را دوباره حساب میکند | struct هماهنگکننده یا goroutine مالک state | Action هماهنگکننده؛ event dispatcher |
| Memento | snapshot ذخیره کن و بعداً برگرد، بدون افشای جزئیات | undo تنظیمات، نسخههای سند | struct با فیلدهای unexported | جدول document_versions |
| Visitor | عملیات تازه روی مجموعهٔ ثابتی از نوعها | مالیات و CSV روی سطرهای فاکتور | ast.Walk، ast.Inspect | کلاسهای accept()/visitX() |
| Interpreter | هر قاعدهٔ گرامر یک کلاس؛ درخت را ارزیابی کن | قاعدهٔ تخفیف ذخیرهشده در JSON | interface Expr با Eval | کلاسهای قاعده که parser میسازد |
اشتباهگرفتنهایی که همه دارند. هر جفت در انتخاب حل میشود.
| شبیه به هم | تفاوت در یک خط |
|---|---|
| Strategy و State | strategy را فراخواننده انتخاب میکند؛ state خودش وضعیت بعدی را انتخاب میکند |
| Strategy و Template Method | ترکیب (Composition) و تعویض در زمان اجرا، در برابر وراثت و مرحلههای زمان کامپایل |
| Observer و pub/sub | Observer: subject رابط observerها را میشناسد، درون یک پردازه؛ pub/sub: یک broker در میان، هیچ طرف دیگری را نمیشناسد |
| Observer و Mediator | Observer پخش یکبهچند است؛ Mediator قواعد هماهنگی چندبهچند را در خود دارد |
| Command و Job و Transaction Script | Command الگوست؛ Job در Laravel یک Command صفشده است؛ Transaction Script یک procedure برای هر درخواست است، بدون object برای درخواست |
| Chain و Decorator | handlerهای زنجیره میتوانند درخواست را متوقف کنند؛ decorator همیشه پاس میدهد و رفتار اضافه میکند |
| Memento و undo با Command | Memento حالت قبلی را نگه میدارد؛ Command راه برگشت را |
| Iterator و Visitor | Iterator ترتیب عناصر را تعیین میکند؛ Visitor تعیین میکند با هر نوع چه کنیم |
نقشه الگوها را بر اساس سؤالی که جواب میدهند گروهبندی میکند: چه چیزی تغییر میکند (یک الگوریتم)، چه چیزی حرکت میکند (یک درخواست)، روی چه چیزی پیمایش میشود (یک ساختار)، و چه چیزی به خاطر سپرده میشود (حالت).
چرا الگوهای رفتاری وجود دارند
کدی که روز اول کار میکند معمولاً رفتارش سیمکشی ثابت دارد: یک switch روی روش ارسال، یک controller که در یک متد validate و authorize و charge و ایمیل میکند، و if ($order->status === 'paid') در بیست جا. هر نیاز تازه همان کد را ویرایش میکند. الگوهای رفتاری بخش متغیر را (یک الگوریتم، یک handler، یک واکنش، یک وضعیت) به object یا تابع خودش منتقل میکنند تا نیاز تازه یک قطعهٔ تازه باشد، نه یک شاخهٔ دیگر.
| رفتار سیمکشیشده | رفتار به شکل قطعههای قابلتعویض |
|---|---|
| کل جریان در یک جا خوانده میشود | جریان بین چند نوع کوچک پخش است |
حالت تازه = ویرایش switch در همهجا | حالت تازه = نوع یا تابع تازه، یکبار ثبتشده |
| فرستنده همهٔ واکنشها را میشناسد | فرستنده اعلام میکند؛ واکنشها مشترک میشوند |
| تست به کل جریان نیاز دارد | هر قطعه با یک همسایهٔ جعلی تست میشود |
| بدون واسطه، سریع برای نوشتن | واسطه (Indirection): نامهای بیشتر، پرش بیشتر در IDE |
| خطر: shotgun surgery و زنجیرهٔ if | خطر: الگو برای مسئلهای که ندارید |
تمثیلی که در کل صفحه به آن برمیگردیم: فرودگاه. بازرسی امنیتی چند ایست پشتسرهم دارد و هر کدام میتواند شما را برگرداند (Chain of Responsibility). کارت پرواز درخواستی است که روی کاغذ نوشته شده و هر گیتی بعداً میتواند پردازشش کند (Command). تابلوی پروازها تغییر گیت را به همهٔ کسانی که نگاهش میکنند اعلام میکند (Observer). هواپیماها با هم حرف نمیزنند، با برج مراقبت حرف میزنند (Mediator). پرواز در حال سوارکردن، پریده یا لغوشده است و کاری که مجازید بکنید به همین بستگی دارد (State). شرکت هواپیمایی برای قیمت صندلی شما یک الگوریتم انتخاب میکند (Strategy). نوار چمدان، چمدانها را یکییکی تحویل میدهد بدون اینکه سالن مرتبسازی را نشانتان بدهد (Iterator).
سه بدفهمی رایج، از همین اول
- «الگو یعنی کلاسهایی که باید بنویسید.» الگو راهحل یک مسئلهٔ تکراری است. در Go بیشتر الگوهای رفتاری یک نوع تابعاند: strategy یک
funcاست، chain یکfunc(http.Handler) http.Handler، iterator یکiter.Seq. نوشتن نمودار کلاس کتابی در Go معمولاً بوی بد است. - «الگوی بیشتر = طراحی بهتر.» هر الگو واسطه اضافه میکند. یک
switchبا سه حالت پایدار از یک سلسلهمراتب Strategy روشنتر است. الگو را وقتی به کار ببرید که تغییرپذیری واقعی و تکراری است. - «Observer و pub/sub و event bus و message broker یکیاند.» همه ایدهٔ «اعلام کن بهجای صدا زدن» را دارند، اما در اینکه چه کسی چه کسی را میشناسد، اینکه تحویل همزمان است یا نه، و اینکه پیام از crash جان سالم به در میبرد یا نه، فرق دارند. Observer و pub/sub را ببینید.
از کجا آمده
کتاب GoF، ۱۹۹۴. کتاب Design Patterns: Elements of Reusable Object-Oriented Software نوشتهٔ Erich Gamma، Richard Helm، Ralph Johnson و John Vlissides بیستوسه الگو را در سه خانواده فهرست کرد. فصل رفتاری آن (فصل ۵) یازده الگو دارد: Chain of Responsibility، Command، Interpreter، Iterator، Mediator، Memento، Observer، State، Strategy، Template Method و Visitor. متن خود کتاب را برای این صفحه نخواندیم؛ اطلاعات انتشار از مقالهٔ Wikipedia دربارهٔ کتاب است که میگوید کتاب «started at a birds-of-a-feather session at the 1990 OOPSLA meeting» و «was originally published on 21 October 1994». همان مقاله قاعدهٔ مرکزی کتاب را نقل میکند که توضیح میدهد چرا بیشتر الگوهای رفتاری بر ترکیب (Composition) بنا شدهاند:
"Favor 'object composition' over 'class inheritance'." — Gang of Four، به نقل از Wikipedia، Design Patterns
Template Method تنها الگوی رفتاری مبتنی بر وراثت (Inheritance) است؛ بقیه کار را به object دیگری واگذار (Delegate) میکنند. به همین دلیل Go که وراثت ندارد همهٔ آنها را راحت پیاده میکند.
آنچه نویسندگان عوض میکردند. Wikipedia گزارش میکند Erich Gamma در مصاحبهٔ ۲۰۰۹ با InformIT گفته نویسندگان برخی الگوها را دوباره دستهبندی و الگوهایی مثل dependency injection و null object را اضافه میکردند. الگوها یک واژگاناند، نه فهرستی بسته.
refactoring.guru. کاتالوگ Alexander Shvets پرخوانندهترین بازگویی امروزی است، با نمودار ساختار و مثال در Go و PHP. جملهٔ هدف (Intent) هر الگو در بلوک خودش از آنجا نقل شده است.
قابلیتهای زبان که الگو را جذب کردند. sort.Interface و slices.SortFunc در Go همان Strategy هستند؛ middleware در net/http همان Chain of Responsibility است؛ go/ast یک Visitor (ast.Walk) و شکل closure آن (ast.Inspect) را دارد. Go 1.23 قابلیت range-over-func را آورد و وبلاگ Go میگوید «Range over function types is a new language feature in the Go 1.23 release»؛ با پکیج iter الگوی Iterator به قابلیت زبان تبدیل شد. در PHP، generatorها Iterator را یک کلیدواژه (yield) کردند؛ مستندات Laravel صریحاً میگوید «Laravel's events provide a simple observer pattern implementation» و facade Pipeline همان Chain of Responsibility است که مستندات دربارهٔ آن میگوید «is very similar to middleware».
الگوها، یکییکی
هر بلوک یک ترتیب ثابت دارد: هدف، زبان ساده، باور غلط رایج، ساختار و اجزا، timeline، سناریوهای واقعی، کد Go و Laravel، سپس پیامدها، کی استفاده نکنیم، اشتباهگرفتنها، شکل توزیعشده و تست.
Template Method مهم
"Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure." — refactoring.guru، Template Method
به زبان ساده: دستور پخت ثابت است (header، سطرها، footer) و فقط بعضی مرحلهها در هر نسخه فرق میکنند.
بدفهمی رایج: «هر کلاس پایه با کد مشترک یعنی Template Method.» نکته ترتیب ثابت مرحلهها است که مال کلاس پایه است و زیرکلاسها فقط جاهای خالی را پر میکنند. کلاس پایهای که زیرکلاسهایش کل جریان را override میکنند فقط وراثت است.
تعریف و اجزا: یک کلاس انتزاعی (Abstract Class) با متد قالب (Template Method، اغلب final) که عملیات اولیه (Primitive Operations) یعنی مرحلههای abstract و قلابها (Hooks) یعنی مرحلههای دارای پیشفرض را صدا میزند؛ کلاسهای مشخص (Concrete Classes) مرحلهها را پیاده میکنند. کلاس پایه زیرکلاس را صدا میزند نه برعکس؛ به همین دلیل به آن اصل هالیوود (Hollywood principle) میگویند: «ما را صدا نزن، ما صدایت میزنیم».
Caller ReportExporter (base) MarkdownExporter (subclass)
1 export(rows) -> header() -> "| id | name |"
2 row(r) x N -> "| 1 | mug |"
3 footer(count) -> "2 rows" (hook overridden)
4 <- full string order of 1..3 never changesسناریوی واقعی: exporterهای گزارش (CSV، Markdown، PDF) با جریان مشترک fetch-format-write؛ importerهایی که parse و validate و ذخیره میکنند؛ کلاسهای پایهٔ تست (setUp، تست، tearDown) در PHPUnit؛ چرخهٔ عمر فریمورکها مثل Command::handle در Laravel که run() فریمورک دورش را گرفته.
Go: وراثت نیست، پس اسکلت یک تابع میشود و مرحلهها یک interface. ترتیب همچنان در یک جا ثابت است.
// Package templatemethod shows Template Method the Go way: the skeleton is a
// function, the varying steps are an interface (or func fields), not a base class.
package templatemethod
import (
"fmt"
"io"
"strings"
)
// Steps are the hooks the skeleton calls. Each exporter supplies its own.
type Steps interface {
Header(w io.Writer) error
Row(w io.Writer, cells []string) error
Footer(w io.Writer, rows int) error
}
// Export is the template method: the order of steps is fixed here and
// cannot be changed by an exporter.
func Export(w io.Writer, s Steps, rows [][]string) error {
if err := s.Header(w); err != nil {
return fmt.Errorf("header: %w", err)
}
for _, r := range rows {
if err := s.Row(w, r); err != nil {
return fmt.Errorf("row: %w", err)
}
}
return s.Footer(w, len(rows)) // hook with a default-like role
}
// CSV is one concrete set of steps.
type CSV struct{ Columns []string }
func (c CSV) Header(w io.Writer) error {
_, err := fmt.Fprintln(w, strings.Join(c.Columns, ","))
return err
}
func (CSV) Row(w io.Writer, cells []string) error {
_, err := fmt.Fprintln(w, strings.Join(cells, ","))
return err
}
func (CSV) Footer(io.Writer, int) error { return nil } // CSV has no footer
// Markdown reuses the same skeleton with different steps.
type Markdown struct{ Columns []string }
func (m Markdown) Header(w io.Writer) error {
_, err := fmt.Fprintf(w, "| %s |\n|%s\n", strings.Join(m.Columns, " | "),
strings.Repeat(" --- |", len(m.Columns)))
return err
}
func (Markdown) Row(w io.Writer, cells []string) error {
_, err := fmt.Fprintf(w, "| %s |\n", strings.Join(cells, " | "))
return err
}
func (Markdown) Footer(w io.Writer, rows int) error {
_, err := fmt.Fprintf(w, "\n%d rows\n", rows)
return err
}Laravel: یک abstract class با متد قالب final و یک hook با پیشفرض.
<?php
// Template Method: the base class fixes the order of steps (final export()),
// subclasses fill in the steps. In a real app each class has its own file.
namespace App\Reports;
use Illuminate\Support\Collection;
abstract class ReportExporter
{
/** The template method: final, so no subclass can reorder the steps. */
final public function export(Collection $rows): string
{
$out = $this->header();
foreach ($rows as $row) {
$out .= $this->row($row);
}
return $out.$this->footer($rows->count());
}
abstract protected function header(): string;
abstract protected function row(array $row): string;
/** Hook: a default that subclasses may override. */
protected function footer(int $count): string
{
return '';
}
}
final class CsvExporter extends ReportExporter
{
public function __construct(private readonly array $columns) {}
protected function header(): string
{
return implode(',', $this->columns)."\n";
}
protected function row(array $row): string
{
return implode(',', $row)."\n";
}
}
final class MarkdownExporter extends ReportExporter
{
public function __construct(private readonly array $columns) {}
protected function header(): string
{
return '| '.implode(' | ', $this->columns)." |\n|"
.str_repeat(' --- |', count($this->columns))."\n";
}
protected function row(array $row): string
{
return '| '.implode(' | ', $row)." |\n";
}
protected function footer(int $count): string
{
return "\n{$count} rows\n";
}
}پیامدها: جریان تکراری حذف و ترتیب اجباری میشود. هزینه: وراثت زیرکلاسها را به پایه میچسباند؛ سلسلهمراتب عمیق دنبالکردن جریان را سخت میکند؛ زیرکلاس میتواند فرضهای پایه را بشکند (ریسک LSP).
کی استفاده نکنیم: وقتی نسخهها در بیش از دو سه مرحله فرق دارند (برای هر مرحله object از نوع Strategy بگذارید)، یا وقتی باید نسخه را در زمان اجرا عوض کنید.
مرتبط / اشتباهگرفته با: Strategy و Template Method؛ Factory Method اغلب یکی از مرحلههای یک template method است (Creational Patterns). شکل توزیعشده ندارد: الگویی برای ساختار کد است.
تست: اسکلت را یکبار با Steps جعلی تست کنید؛ هر exporter مشخص را با خروجیاش (فایل export_test.go در ماژول).
Chain of Responsibility حیاتی
"Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain." — refactoring.guru، Chain of Responsibility
به زبان ساده: صفی از ایستهای بازرسی. هر کدام درخواست را نگاه میکند و یا رسیدگی میکند، یا ردش میکند، یا جلو میفرستد.
بدفهمی رایج: «در زنجیره فقط یک handler کار میکند.» شکل GoF در اولین handler که میتواند رسیدگی کند متوقف میشود (زنجیرهٔ تأیید). شکل middleware اجازه میدهد هر handler کار کند و جلو بفرستد (logging، auth، rate limiting) و حق توقف هم دارد. هر دو Chain of Responsibility هستند.
تعریف و اجزا: interface یک رسیدگیکننده (Handler) با ارجاع به handler بعدی (یا closure $next)؛ handlerهای مشخص؛ یک client که زنجیره را میسازد و درخواست را به سر آن میفرستد. زنجیره در زمان اجرا سرهم میشود، پس ترتیب و اعضا پیکربندیاند.
Request GET /orders without token
1 Client -> Logging.handle logs "GET /orders", calls next
2 RequireToken.handle no Authorization header -> writes 401, returns
3 RateLimit, controller never run
4 Client <- 401 (Logging sees the response on the way back)سناریوی واقعی: middlewareهای HTTP (auth، CSRF، CORS، rate limit، tenancy)؛ تأیید خرید بر اساس مبلغ (سرپرست تیم، مدیر، CFO)؛ ارجاع تیکت پشتیبانی به سطح بالاتر؛ قواعد fraud که هر کدام میتوانند پرداخت را بلاک کنند؛ handlerهای log که هر کدام تصمیم میگیرند رکورد بنویسند یا نه.
Go: middleware در net/http زنجیرهٔ استاندارد است. مستندات Go آداپتوری را که بر آن بنا شده توصیف میکند: «The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers.» زنجیرهٔ تأیید شکل «اولین کسی که میتواند تصمیم بگیرد» را نشان میدهد.
// Package chain shows Chain of Responsibility twice: the net/http middleware
// chain (every handler may stop the request) and an approval chain (the first
// handler that can decide, decides).
package chain
import (
"errors"
"log/slog"
"net/http"
)
// Middleware wraps a handler; the wrapped handler is "next".
type Middleware func(next http.Handler) http.Handler
// Chain applies middlewares so that the first one listed runs first.
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// RequireToken stops the chain when the header is missing.
func RequireToken(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return // the request never reaches next
}
next.ServeHTTP(w, r)
})
}
// statusRecorder remembers the status code written by later handlers.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
// Logging always passes the request on and logs the result on the way back.
func Logging(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Info("request", "method", r.Method, "path", r.URL.Path, "status", rec.status)
})
}
}
// Approver is one link of an approval chain.
type Approver struct {
Role string
Limit int64 // highest amount this role may approve, in cents
Next *Approver
}
// ErrNoApprover means the request fell off the end of the chain.
var ErrNoApprover = errors.New("no approver can handle this amount")
// Approve walks the chain until a link can decide.
func (a *Approver) Approve(amount int64) (string, error) {
for link := a; link != nil; link = link.Next {
if amount <= link.Limit {
return link.Role, nil
}
}
return "", ErrNoApprover
}
// NewApprovalChain builds team lead -> manager -> CFO.
func NewApprovalChain() *Approver {
cfo := &Approver{Role: "cfo", Limit: 10_000_000}
manager := &Approver{Role: "manager", Limit: 500_000, Next: cfo}
return &Approver{Role: "team-lead", Limit: 50_000, Next: manager}
}Laravel: middleware زنجیرهٔ HTTP است (مستندات Laravel: «It's best to envision middleware as a series of "layers" HTTP requests must pass through»)؛ facade Pipeline همین شکل را برای هر objectی میدهد. آزمایشگاه برای checkout از Pipeline استفاده میکند.
<?php
// Chain of Responsibility in Laravel: route middleware and the Pipeline facade
// are the same shape: each handler gets the input and a $next closure.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class EnsureApiToken
{
public function handle(Request $request, Closure $next): Response
{
if (! $request->bearerToken()) {
return response()->json(['message' => 'Unauthorized'], 401); // chain stops
}
return $next($request); // pass to the next handler
}
}
namespace App\Approvals;
use InvalidArgumentException;
/** A classic approval chain: the first link that can decide, decides. */
abstract class Approver
{
private ?Approver $next = null;
public function then(Approver $next): Approver
{
$this->next = $next;
return $next;
}
public function approve(int $cents): string
{
if ($this->canApprove($cents)) {
return static::class;
}
return $this->next?->approve($cents)
?? throw new InvalidArgumentException("No approver for {$cents}");
}
abstract protected function canApprove(int $cents): bool;
}
final class TeamLead extends Approver
{
protected function canApprove(int $cents): bool
{
return $cents <= 50_000;
}
}
final class Manager extends Approver
{
protected function canApprove(int $cents): bool
{
return $cents <= 500_000;
}
}
final class Cfo extends Approver
{
protected function canApprove(int $cents): bool
{
return $cents <= 10_000_000;
}
}
// Usage:
// $chain = new TeamLead;
// $chain->then(new Manager)->then(new Cfo);
// $chain->approve(200_000); // App\Approvals\Managerپیامدها: فرستنده از handlerها جدا میشود؛ handlerها تکمنظوره و قابل جابهجاییاند (SRP، OCP). هزینه: ممکن است درخواست بیرسیدگی از انتهای زنجیره بیفتد (خطای صریح مثل ErrNoApprover برگردانید)؛ باگ ترتیب بیصداست (auth بعد از logging مسیرهای احرازنشده را به log میبرد)؛ زنجیرهٔ بلند بدون tracing سخت دیباگ میشود.
کی استفاده نکنیم: جریان ثابت دومرحلهای؛ یا وقتی همهٔ مرحلهها باید همیشه اجرا شوند و هیچکدام حق توقف ندارد (این یک فهرست ساده از توابع است، یا Decorator).
شکل توزیعشده: زنجیرهٔ filter در API gateway؛ routing slip که پیام فهرست مرحلههای پردازشش را با خودش حمل میکند.
مرتبط / اشتباهگرفته با: Decorator (Structural Patterns) همیشه پاس میدهد، حلقهٔ زنجیره میتواند متوقف کند؛ برای شکلهای دیگر فرستنده/گیرنده Observer و Mediator.
تست: هر handler را با next جعلی تست کنید (اینکه صدا زده شد یا نه)؛ زنجیرهٔ سرهمشده را با httptest برای باگ ترتیب تست کنید و بررسی کنید Logging بیرونی 401 را دید (chain_test.go).
State حیاتی
"State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class." — refactoring.guru، State
به زبان ساده: سفارشی که paid است میتواند ارسال شود؛ سفارش pending نمیتواند. بهجای if status == در همهجا، هر وضعیت یک object است که میداند چه چیزی مجاز است و بعدش چه میآید.
بدفهمی رایج: «ستون status همان الگوی State است.» ستون داده است. الگو این است که قواعد کجا زندگی میکنند: در یک جا برای هر وضعیت (یا یک جدول transition)، نه در ifهای پخششده در controller و job و view.
تعریف و اجزا: یک زمینه (Context) مثل Order که به یک object وضعیت (State) اشاره دارد؛ interface وضعیت با یک متد برای هر عمل؛ وضعیتهای مشخص که هر عمل را پیاده میکنند و معمولاً وضعیت context را عوض میکنند. مدل پشت آن ماشین حالت متناهی (Finite State Machine) است: مجموعهای از وضعیتها، رویدادها و گذارها (Transitions)؛ گذار غیرمجاز رد میشود.
Order 42 (PostgreSQL, READ COMMITTED) Worker A (payment webhook) Worker B (admin cancels)
1 status = 'pending' reads pending
2 reads pending
3 UPDATE ... SET status='paid' WHERE status='pending' -> 1 row
4 UPDATE ... SET status='cancelled' WHERE status='pending' -> 0 rows
5 transition rejected: refund not needed, no lost updateسناریوی واقعی: چرخهٔ عمر سفارش (pending، paid، shipped، delivered، cancelled، refunded)؛ صورتحساب اشتراک (trialing، active، past_due، cancelled)؛ تأیید سند (draft، in review، approved، published)؛ اتصال شبکه (closed، listening، established)؛ وضعیتهای rollout یک feature.
Go: state به شکل interface؛ هر نوع وضعیت گذار را تعیین میکند. آزمایشگاه شکل رایج دیگر در Go را نشان میدهد: جدول transition بهصورت داده.
// Package state shows the State pattern: each order state is a type that
// knows which transitions it allows; the Order delegates to its current state.
package state
import (
"errors"
"fmt"
)
// ErrTransition is returned for an action the current state does not allow.
var ErrTransition = errors.New("transition not allowed")
// State is the behaviour that changes when the order's state changes.
type State interface {
Name() string
Pay(o *Order) error
Ship(o *Order) error
Cancel(o *Order) error
}
// Order is the context.
type Order struct {
ID string
state State
}
func New(id string) *Order { return &Order{ID: id, state: pending{}} }
func (o *Order) Status() string { return o.state.Name() }
func (o *Order) Pay() error { return o.state.Pay(o) }
func (o *Order) Ship() error { return o.state.Ship(o) }
func (o *Order) Cancel() error { return o.state.Cancel(o) }
func (o *Order) set(next State) { o.state = next }
func deny(s State, action string) error {
return fmt.Errorf("%w: %s from %s", ErrTransition, action, s.Name())
}
// Deliver and Refund follow the same shape and are omitted here; the lab
// package shows the full machine as a transition table.
type pending struct{}
func (pending) Name() string { return "pending" }
func (pending) Pay(o *Order) error { o.set(paid{}); return nil }
func (s pending) Ship(*Order) error { return deny(s, "ship") }
func (pending) Cancel(o *Order) error { o.set(cancelled{}); return nil }
type paid struct{}
func (paid) Name() string { return "paid" }
func (s paid) Pay(*Order) error { return deny(s, "pay") }
func (paid) Ship(o *Order) error { o.set(shipped{}); return nil }
func (s paid) Cancel(*Order) error { return deny(s, "cancel") } // paid orders are refunded, not cancelled
type shipped struct{}
func (shipped) Name() string { return "shipped" }
func (s shipped) Pay(*Order) error { return deny(s, "pay") }
func (s shipped) Ship(*Order) error { return deny(s, "ship") }
func (s shipped) Cancel(*Order) error { return deny(s, "cancel") }
type cancelled struct{}
func (cancelled) Name() string { return "cancelled" }
func (s cancelled) Pay(*Order) error { return deny(s, "pay") }
func (s cancelled) Ship(*Order) error { return deny(s, "ship") }
func (s cancelled) Cancel(*Order) error { return deny(s, "cancel") }Laravel: یک backed enum وضعیت است، transitions() ماشین است، و enum cast در Eloquent ذخیرهاش میکند. بهروزرسانی مشروط به وضعیت قبلی است، پس دو worker نمیتوانند هر دو گذار را انجام دهند.
<?php
// State with a PHP 8.1+ backed enum: the enum is the state, transitions()
// is the state machine, and the model refuses illegal moves.
namespace App\Enums;
enum OrderStatus: string
{
case Pending = 'pending';
case Paid = 'paid';
case Shipped = 'shipped';
case Delivered = 'delivered';
case Cancelled = 'cancelled';
case Refunded = 'refunded';
/** @return list<self> */
public function transitions(): array
{
return match ($this) {
self::Pending => [self::Paid, self::Cancelled],
self::Paid => [self::Shipped, self::Refunded],
self::Shipped => [self::Delivered],
self::Delivered, self::Cancelled, self::Refunded => [],
};
}
public function canTransitionTo(self $next): bool
{
return in_array($next, $this->transitions(), true);
}
/** State-dependent behaviour lives on the state, not in if-chains. */
public function customerCanCancel(): bool
{
return $this === self::Pending;
}
}
namespace App\Models;
use App\Enums\OrderStatus;
use App\Events\OrderStatusChanged;
use DomainException;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = ['customer_id', 'total', 'status'];
protected function casts(): array
{
return ['status' => OrderStatus::class]; // Eloquent enum casting
}
public function transitionTo(OrderStatus $next): void
{
if (! $this->status->canTransitionTo($next)) {
throw new DomainException("Cannot move order {$this->id} from {$this->status->value} to {$next->value}");
}
$from = $this->status;
// Guard against a concurrent transition: only update if still in $from.
$updated = static::whereKey($this->id)
->where('status', $from->value)
->update(['status' => $next->value]);
if ($updated === 0) {
throw new DomainException("Order {$this->id} changed concurrently");
}
$this->status = $next;
$this->syncOriginalAttribute('status');
OrderStatusChanged::dispatch($this, $from, $next);
}
}پیامدها: قواعد هر وضعیت در یک جا؛ گذار غیرمجاز از اساس ناممکن؛ وضعیت تازه یعنی نوع تازه، نه ویرایش همهٔ ifها. هزینه: نوعهای کوچک زیاد برای چرخههای ساده؛ گذارهای پخششده در کلاسهای وضعیت سختتر از یک جدول دیده میشوند (برای همین خیلی از تیمها شکل جدولی را ترجیح میدهند).
کی استفاده نکنیم: دو وضعیت و یک گذار (یک boolean کافی است)؛ یا وقتی رفتار واقعاً به وضعیت بستگی ندارد.
شکل توزیعشده: saga یک state machine است که گذارهایش پیام بین سرویسهاست؛ موتورهای workflow مثل Temporal ماشین را برایتان پایدار میکنند (Durable Workflows).
مرتبط / اشتباهگرفته با: Strategy و State؛ state machine بین سرویسها یک saga است.
تست: تست جدولی روی همهٔ جفتهای (from، to) و یک تست برای هر گذار غیرمجاز (order_test.go، lab_test.go)؛ حالت همزمان (دو گذار از یک وضعیت) آزمایش ۶ آزمایشگاه روی PostgreSQL است.
Command حیاتی
"Command is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations." — refactoring.guru، Command
به زبان ساده: بهجای اینکه همین حالا charge(order) را صدا بزنید، روی یک کارت مینویسید «سفارش ۴۲ را charge کن». کارت را میشود الان، بعداً، روی ماشین دیگر، دوباره برای retry، یا برعکس اجرا کرد.
بدفهمی رایج: «Command یعنی دستور CLI.» دستورهای Artisan و Cobra از همین ایده نام گرفتهاند اما الگو وسیعتر است: هر درخواستی به شکل object (یک Job در Laravel، DTO درخواست HTTP که به handler داده میشود، عمل ویرایشگر با undo).
تعریف و اجزا: interface فرمان (Command) (execute و اختیاری undo)؛ فرمانهای مشخص که پارامترها را نگه میدارند؛ گیرنده (Receiver) که کار واقعی را میکند؛ فراخواننده (Invoker) که فرمانها را اجرا میکند (دکمه، queue worker، history)؛ client که فرمان میسازد. چون درخواست داده است، میشود serialize، صف، log، retry و undo کرد.
Editor (History invoker) Undo stack Redo stack Doc.Text
1 Execute(Insert "hello") [Insert] [] "hello"
2 Execute(Replace "bye") [Insert, Replace] [] "bye"
3 Undo() [Insert] [Replace] "hello"
4 Redo() [Insert, Replace] [] "bye"
5 Execute(Insert "!") [.., Insert] [] cleared "bye!"سناریوی واقعی: jobهای صفشده (ارسال فاکتور، capture پرداخت، تغییر اندازهٔ تصویر)؛ undo/redo در ویرایشگرها؛ ضبط macro؛ audit logی که هر فرمان کاربر را ذخیره میکند؛ retry عملیات شکستخورده؛ زمانبندی (scheduler در Laravel jobها را طبق جدول اجرا میکند: Schedule::job(new Heartbeat)->everyFiveMinutes()).
Go: فرمانها مقدارهایی با Do/Undo، یک invoker به نام History با دو پشته (Stack)، و log بهعنوان محصول جانبی.
// Package command shows Command with undo/redo: every edit is an object that
// knows how to apply and revert itself, and History keeps two stacks.
package command
import "errors"
// Doc is the receiver: the thing commands act on.
type Doc struct{ Text string }
// Command is a request turned into a value.
type Command interface {
Do(d *Doc)
Undo(d *Doc)
Name() string // stored in the audit log
}
// Insert appends text at the end.
type Insert struct{ S string }
func (c Insert) Do(d *Doc) { d.Text += c.S }
func (c Insert) Undo(d *Doc) { d.Text = d.Text[:len(d.Text)-len(c.S)] }
func (c Insert) Name() string { return "insert" }
// Replace swaps the whole text; it remembers what it replaced so Undo works.
type Replace struct {
S string
old string
}
func (c *Replace) Do(d *Doc) { c.old, d.Text = d.Text, c.S }
func (c *Replace) Undo(d *Doc) { d.Text = c.old }
func (c *Replace) Name() string { return "replace" }
// ErrEmpty is returned when there is nothing to undo or redo.
var ErrEmpty = errors.New("nothing to undo or redo")
// History is the invoker: it executes commands and keeps undo/redo stacks.
type History struct {
doc *Doc
undo, redo []Command
Log []string // command history doubles as an audit log
}
func NewHistory(d *Doc) *History { return &History{doc: d} }
func (h *History) Execute(c Command) {
c.Do(h.doc)
h.undo = append(h.undo, c)
h.redo = h.redo[:0] // a new command invalidates the redo branch
h.Log = append(h.Log, "do "+c.Name())
}
func (h *History) Undo() error {
if len(h.undo) == 0 {
return ErrEmpty
}
c := h.undo[len(h.undo)-1]
h.undo = h.undo[:len(h.undo)-1]
c.Undo(h.doc)
h.redo = append(h.redo, c)
h.Log = append(h.Log, "undo "+c.Name())
return nil
}
func (h *History) Redo() error {
if len(h.redo) == 0 {
return ErrEmpty
}
c := h.redo[len(h.redo)-1]
h.redo = h.redo[:len(h.redo)-1]
c.Do(h.doc)
h.undo = append(h.undo, c)
h.Log = append(h.Log, "redo "+c.Name())
return nil
}Laravel: یک Job صفشده همان Command است: پارامترهای constructor درخواستاند، handle() گیرنده را با injection میگیرد، queue worker فراخواننده است. dispatchSync همان فرمان را بدون صف اجرا میکند؛ Bus::chain فرمانها را پشتسرهم اجرا میکند. نیمهٔ دوم یک فرمان ویرایشگر undoپذیر با command log پایدار نشان میدهد.
<?php
// Command in Laravel: a queued Job is a request turned into an object that
// can be serialized, queued, retried, chained and logged.
namespace App\Jobs;
use App\Models\Order;
use App\Services\Payments;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
final class CapturePayment implements ShouldQueue
{
use Queueable;
public int $tries = 5;
public function __construct(public Order $order) {}
/** The receiver (Payments) is injected when the worker runs the command. */
public function handle(Payments $payments): void
{
$payments->capture($this->order->id, $this->order->total, idempotencyKey: "capture-{$this->order->id}");
}
}
// Dispatch now, later, or as a chain of commands:
// CapturePayment::dispatch($order);
// CapturePayment::dispatchSync($order); // same command, no queue
// Bus::chain([new CapturePayment($order), new ShipOrder($order)])->dispatch();
namespace App\Editing;
use App\Models\Document;
use Illuminate\Support\Facades\DB;
/** An undoable command for an editor, with its history stored as rows. */
interface UndoableCommand
{
public function execute(Document $doc): void;
public function undo(Document $doc): void;
}
final class RenameDocument implements UndoableCommand
{
private ?string $previous = null;
public function __construct(private readonly string $title) {}
public function execute(Document $doc): void
{
$this->previous = $doc->title;
$doc->update(['title' => $this->title]);
}
public function undo(Document $doc): void
{
$doc->update(['title' => $this->previous]);
}
}
final class CommandHistory
{
/** @var list<UndoableCommand> */
private array $undo = [];
public function run(UndoableCommand $command, Document $doc, int $userId): void
{
DB::transaction(function () use ($command, $doc, $userId) {
$command->execute($doc);
// Audit log: every command is a row (see the command_log table on the page).
DB::table('command_log')->insert([
'document_id' => $doc->id,
'user_id' => $userId,
'command' => $command::class,
'payload' => json_encode(['title' => $doc->title]),
'created_at' => now(),
]);
});
$this->undo[] = $command;
}
public function undo(Document $doc): void
{
array_pop($this->undo)?->undo($doc);
}
}پیامدها: «تصمیم به انجام» از «انجام» جدا میشود؛ صف، retry، undo، audit و replay ممکن میشود. هزینه: یک کلاس برای هر عمل؛ undo برای اثرهای جانبی بیرون از کنترل شما سخت است (ایمیل را نمیشود پس گرفت: به یک فرمان جبرانی نیاز دارید)؛ فرمانهای serializeشده باید با نسخههای قدیمی که هنوز در صفاند سازگار بمانند.
کی استفاده نکنیم: فراخوانی همزمان بدون نیاز به صف، undo، log یا retry. یک فراخوانی ساده هم یک «فرمان» خوب است.
شکل توزیعشده: پیام روی یک صف همان فرمان serializeشده است؛ idempotency key تحویل دوباره را امن میکند (Idempotent Consumers، Laravel Queue Internals).
مرتبط / اشتباهگرفته با: Command و Job و Transaction Script؛ Memento برای undo مبتنی بر snapshot (پشتههای undo).
تست: فرمان را روی گیرندهٔ جعلی اجرا کنید؛ برای undo بررسی کنید do و بعد undo حالت اصلی را برمیگرداند؛ برای jobها Queue::fake() / Bus::fake() و Bus::assertChained (مستندات Laravel، Queues → Testing).
Observer حیاتی
"Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing." — refactoring.guru، Observer
به زبان ساده: «سفارش پرداخت شد» یکبار اعلام میشود؛ فرستندهٔ ایمیل، انبار و کد analytics هر کدام گوش میدهند. سفارش نمیداند چه کسی گوش میدهد.
بدفهمی رایج: «observerها ناهمزماناند.» Observer کلاسیک همزمان است: Notify هر observer را در thread خود subject صدا میزند و observer کند یا خطادار، subject را کند میکند یا میشکند. listenerهای Laravel هم همزماناند مگر ShouldQueue را پیاده کنند.
تعریف و اجزا: یک موضوع (Subject) یا ناشر (Publisher) با subscribe و unsubscribe و notify؛ interface ناظر (Observer) یا مشترک (Subscriber)؛ observerهای مشخص. subject فقط به interface ناظر وابسته است، پس واکنش تازه به تغییر آن نیاز ندارد (OCP). refactoring.guru: «You can introduce new subscriber classes without having to change the publisher’s code»
OrderService (subject) RecordStatusHistory (sync) SendPaidEmail (ShouldQueue)
1 BEGIN; status -> paid
2 dispatch OrderStatusChanged -- ShouldDispatchAfterCommit: held until commit --
3 COMMIT
4 listeners run -> INSERT order_status_history pushed to queue, returns at once
5 worker sends email later (retries on failure)سناریوی واقعی: رویدادهای دامنه (Domain Events) در یک monolith (سفارش پرداخت شد، کاربر ثبتنام کرد)؛ invalidate کردن cache هنگام ذخیرهٔ model (Eloquent observer)؛ data binding در UI؛ پخش webhook؛ قلابهای metrics و audit.
Go: یک subject تایپشده با callbackهای همزمان و تابع unsubscribe، بهعلاوهٔ پخش با channel که در آن channel پر، ناشر را بلاک میکند (backpressure عمدی).
// Package observer shows Observer in Go: a typed, in-process subject with
// synchronous observers and an unsubscribe function, plus a channel fan-out.
package observer
import "sync"
// Subject holds observers of events of type E.
type Subject[E any] struct {
mu sync.RWMutex
next int
observers map[int]func(E)
}
// Subscribe registers fn and returns a function that removes it.
func (s *Subject[E]) Subscribe(fn func(E)) (unsubscribe func()) {
s.mu.Lock()
defer s.mu.Unlock()
if s.observers == nil {
s.observers = map[int]func(E){}
}
id := s.next
s.next++
s.observers[id] = fn
return func() {
s.mu.Lock()
delete(s.observers, id)
s.mu.Unlock()
}
}
// Notify calls every observer synchronously, in the caller's goroutine.
// Observers must be fast; slow work belongs on a queue (see Fanout).
func (s *Subject[E]) Notify(e E) {
s.mu.RLock()
fns := make([]func(E), 0, len(s.observers))
for _, fn := range s.observers {
fns = append(fns, fn)
}
s.mu.RUnlock()
for _, fn := range fns {
fn(e)
}
}
// Fanout delivers each event to every subscriber channel. A full channel
// blocks the publisher: that is backpressure, chosen on purpose here.
type Fanout[E any] struct {
mu sync.Mutex
subs []chan E
}
func (f *Fanout[E]) Subscribe(buffer int) <-chan E {
ch := make(chan E, buffer)
f.mu.Lock()
f.subs = append(f.subs, ch)
f.mu.Unlock()
return ch
}
func (f *Fanout[E]) Publish(e E) {
f.mu.Lock()
defer f.mu.Unlock()
for _, ch := range f.subs {
ch <- e
}
}
// Close ends every subscriber's range loop.
func (f *Fanout[E]) Close() {
f.mu.Lock()
defer f.mu.Unlock()
for _, ch := range f.subs {
close(ch)
}
f.subs = nil
}Laravel: کلاس event، listenerهای همزمان و صفشده، و یک Eloquent observer (ثبتشده با #[ObservedBy([ProductObserver::class])]). ShouldDispatchAfterCommit باعث میشود event منتظر تراکنش (Transaction) دیتابیس بماند تا listenerها هیچوقت سفارشی را نبینند که بعداً rollback میشود.
<?php
// Observer in Laravel: an event class, listeners that subscribe to it,
// queued listeners for slow work, and Eloquent model observers.
namespace App\Events;
use App\Enums\OrderStatus;
use App\Models\Order;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
/** Listeners run only after the surrounding DB transaction commits. */
final class OrderStatusChanged implements ShouldDispatchAfterCommit
{
use Dispatchable, SerializesModels;
public function __construct(
public Order $order,
public OrderStatus $from,
public OrderStatus $to,
) {}
}
namespace App\Listeners;
use App\Enums\OrderStatus;
use App\Events\OrderStatusChanged;
use App\Mail\OrderPaidMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/** Queued observer: the subject does not wait for the email. */
final class SendPaidEmail implements ShouldQueue
{
public function handle(OrderStatusChanged $event): void
{
if ($event->to !== OrderStatus::Paid) {
return;
}
Mail::to($event->order->customer_email)->send(new OrderPaidMail($event->order));
}
}
/** Synchronous observer: runs in the same request (after commit), in registration order. */
final class RecordStatusHistory
{
public function handle(OrderStatusChanged $event): void
{
DB::table('order_status_history')->insert([
'order_id' => $event->order->id,
'from_status' => $event->from->value,
'to_status' => $event->to->value,
'changed_at' => now(),
]);
}
}
namespace App\Observers;
use App\Models\Product;
use Illuminate\Support\Facades\Cache;
/**
* Eloquent observer: reacts to model lifecycle events.
* Registered with #[ObservedBy([ProductObserver::class])] on the model.
*/
final class ProductObserver
{
public function saved(Product $product): void
{
Cache::forget("product:{$product->id}");
}
public function deleted(Product $product): void
{
Cache::forget("product:{$product->id}");
}
}پیامدها: باز برای واکنشهای تازه؛ subject از کد واکنش جداست. هزینه: جریان کنترل نامرئی میشود («این event را چه کسی رسیدگی میکند؟»)؛ ترتیب بین observerها ضمنی است؛ observerی که exception پرتاب کند جریان subject را قطع میکند؛ observerهایی که هرگز unsubscribe نمیشوند حافظه نشت میدهند (مسئلهٔ lapsed listener)؛ آبشارها (observerی که event دیگری میسازد) سخت فهمیده میشوند.
کی استفاده نکنیم: وقتی subject به نتیجهٔ واکنش نیاز دارد (این فراخوانی است، نه اعلان)، یا وقتی دقیقاً یک واکنش هست که همیشه وجود خواهد داشت.
شکل توزیعشده: بین پردازهها Observer به publish/subscribe از طریق broker تبدیل میشود، با پایداری و تحویل at-least-once؛ Event-Driven Architecture و Transactional Outbox را برای انتشار مطمئن پس از commit ببینید.
مرتبط / اشتباهگرفته با: Observer و pub/sub و Mediator.
تست: Event::fake() و بعد Event::assertDispatched / assertNotDispatched (مستندات Laravel، Events → Testing)؛ در Go یک تابع ضبطکننده subscribe کنید و فراخوانیها را بررسی کنید؛ اینکه unsubscribe کار میکند را هم تست کنید (bus_test.go).
Strategy حیاتی
"Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable." — refactoring.guru، Strategy
به زبان ساده: «هزینهٔ ارسال را چطور حساب کنیم؟» چند جواب دارد؛ checkout یکی از آنها را نگه میدارد و برایش مهم نیست کدام.
بدفهمی رایج: «Strategy به یک interface و یک کلاس برای هر الگوریتم نیاز دارد.» در Go و PHP امروزی strategy اغلب یک تابع است: slices.SortFunc(x, cmp) استراتژی مقایسه را به شکل cmp میگیرد؛ sortBy(fn ...) در Laravel هم همینطور.
تعریف و اجزا: یک زمینه (Context) که به interface استراتژی اشاره دارد و یک کار را به آن واگذار میکند؛ استراتژیهای مشخص؛ یک client (یا container، config، feature flag) که یکی را انتخاب میکند. استراتژیها همدیگر را نمیشناسند.
Request Registry / container Strategy run
1 quote("weight", 2500 g) -> Registry["weight"] -> ceil(2.5) x 300 = 900
2 quote("flat", 2500 g) -> Registry["flat"] -> 500
3 feature flag free=on -> binding switches to Free -> 0 (no change to checkout code)سناریوی واقعی: محاسبهٔ ارسال، مالیات و تخفیف؛ ارائهدهندگان پرداخت (Stripe یا PayPal)؛ سیاستهای retry/backoff؛ مرتبسازی و رتبهبندی؛ فرمت فشردهسازی یا serialization؛ قواعد مجوز (Gateها در Laravel closure هستند و Policyها کلاس: دو شکل strategy برای «آیا این کاربر مجاز است؟»).
Go: stdlib پر از strategy است. sort.Sort یک sort.Interface میگیرد («An implementation of Interface can be sorted by the routines in this package»، مستندات Go) و slices.SortFunc جدیدتر یک تابع.
// Package strategy shows Strategy in Go: a strategy is usually just a
// function value; an interface is used when the strategy has state or
// several methods. sort.Interface and slices.SortFunc are stdlib examples.
package strategy
import (
"cmp"
"fmt"
"slices"
)
// Shipping is the strategy type: one algorithm, many interchangeable bodies.
type Shipping func(weightGrams int) (cents int64)
func Flat(weightGrams int) int64 { return 500 }
func ByWeight(perKg int64) Shipping {
return func(weightGrams int) int64 {
kg := int64((weightGrams + 999) / 1000) // round up
return kg * perKg
}
}
func Free(int) int64 { return 0 }
// Registry picks a strategy by name, e.g. from config or a feature flag.
var Registry = map[string]Shipping{
"flat": Flat,
"weight": ByWeight(300),
"free": Free,
}
// Quote is the context: it does not know which algorithm it runs.
func Quote(method string, weightGrams int) (int64, error) {
s, ok := Registry[method]
if !ok {
return 0, fmt.Errorf("unknown shipping method %q", method)
}
return s(weightGrams), nil
}
type Product struct {
Name string
Price int64
Sold int
}
// SortBy shows the stdlib's own Strategy: the comparison is passed in.
func SortBy(ps []Product, key string) {
byKey := map[string]func(a, b Product) int{
"price": func(a, b Product) int { return cmp.Compare(a.Price, b.Price) },
"popularity": func(a, b Product) int { return cmp.Compare(b.Sold, a.Sold) },
}
if f, ok := byKey[key]; ok {
slices.SortStableFunc(ps, f)
}
}Laravel: یک strategy که با config از طریق binding در container انتخاب میشود، یا همهٔ strategyها از طریق tag. مستندات container در Laravel: «Once the services have been tagged, you may easily resolve them all via the container's tagged method»؛ attribute زمینهای #[Tag('shipping')] آنها را inject میکند.
<?php
// Strategy in Laravel: an interface, interchangeable implementations, and the
// container choosing one (config) or handing you all of them (tags).
namespace App\Shipping;
interface ShippingStrategy
{
public function key(): string;
public function quote(int $grams): int; // cents
}
final class FlatRate implements ShippingStrategy
{
public function key(): string { return 'flat'; }
public function quote(int $grams): int { return 500; }
}
final class ByWeight implements ShippingStrategy
{
public function __construct(private readonly int $perKg = 300) {}
public function key(): string { return 'weight'; }
public function quote(int $grams): int { return (int) ceil($grams / 1000) * $this->perKg; }
}
final class FreeShipping implements ShippingStrategy
{
public function key(): string { return 'free'; }
public function quote(int $grams): int { return 0; }
}
namespace App\Providers;
use App\Shipping\{ByWeight, FlatRate, FreeShipping, ShippingStrategy};
use Illuminate\Support\ServiceProvider;
final class ShippingServiceProvider extends ServiceProvider
{
public function register(): void
{
// One strategy, chosen by configuration:
$this->app->bind(ShippingStrategy::class, fn () => match (config('shop.shipping')) {
'weight' => new ByWeight,
'free' => new FreeShipping,
default => new FlatRate,
});
// All strategies, so the customer can choose at checkout:
$this->app->tag([FlatRate::class, ByWeight::class, FreeShipping::class], 'shipping');
}
}
namespace App\Shipping;
use Illuminate\Container\Attributes\Tag;
use InvalidArgumentException;
/** The context: it knows the strategies only through the interface. */
final class ShippingQuoter
{
/** @param iterable<ShippingStrategy> $strategies */
public function __construct(#[Tag('shipping')] private readonly iterable $strategies) {}
public function quote(string $key, int $grams): int
{
foreach ($this->strategies as $strategy) {
if ($strategy->key() === $key) {
return $strategy->quote($grams);
}
}
throw new InvalidArgumentException("Unknown shipping method {$key}");
}
}
// Collections take strategies as closures, like Go's slices.SortFunc:
// $products->sortBy(fn ($p) => $p->price);
// Gate::define('update-post', [PostPolicy::class, 'update']); // authorization strategyپیامدها: الگوریتم در زمان اجرا عوض میشود؛ هر کدام جدا تست میشود؛ switch در context نیست. هزینه: client باید بداند چه strategyهایی هست تا انتخاب کند؛ نوعهای بیشتر؛ برای دو شاخهٔ پایدار زیادی است.
کی استفاده نکنیم: الگوریتم هرگز عوض نمیشود، یا فقط در زمان کامپایل و درون یک تابع.
مرتبط / اشتباهگرفته با: Strategy و State و Template Method. شکل توزیعشده: انتخاب strategy از یک سرویس مشترک feature flag یا config میآید تا همهٔ نمونهها توافق داشته باشند (دادههای توزیعشده).
تست: یک تست جدولمحور با یک سطر برای هر strategy و assertionهای یکسان (pricing_test.go)؛ منطق انتخاب را جدا تست کنید.
Iterator حیاتی
"Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.)." — refactoring.guru، Iterator
به زبان ساده: «بعدی را بده» بدون اینکه بدانید عناصر از slice، درخت، API صفحهبندیشده یا cursor دیتابیس میآیند.
بدفهمی رایج: «در Go فقط slice داریم، پس Iterator بیربط است.» تا پیش از Go 1.23 تقریباً درست بود و کد streaming از callback یا channel استفاده میکرد. از Go 1.23، iter.Seq Iterator استاندارد است و پکیجهای stdlib (slices، maps، go/ast) آن را برمیگردانند.
تعریف و اجزا: یک پیمایشگر (Iterator) با «بعدی» و «هنوز هست؟» (سبک pull) یا تابعی که هر عنصر را به یک callback هل میدهد (سبک push)؛ یک مجموعه (Aggregate) که iterator میسازد. مستندات Go شکل push را تعریف میکند: «An iterator is a function that passes successive elements of a sequence to a callback function, conventionally named yield. The function stops either when the sequence is finished or when yield returns false, indicating to stop the iteration early.»
for id, err := range Each(ctx, fetch) iterator body
1 fetch(cursor="") -> ids [1 2], next "p2"
2 id=1 -> loop body yield(1) true
3 id=2 -> loop body yield(2) true
4 fetch(cursor="p2") -> ids [3], next "p3"
5 id=3 -> loop body; break yield(3) false -> return, no more fetchesسناریوی واقعی: stream کردن یک میلیون سطر به CSV بدون بارگذاری همه؛ پنهان کردن صفحهبندی API تأمینکننده؛ پیمایش درخت دستهبندی؛ ادغام دو stream مرتب؛ فیلتر تنبل (Lazy) روی logها.
Go: iter.Seq برای درخت، iter.Seq2[int, error] برای API صفحهبندیشده که ممکن است خطا بدهد، و iter.Pull برای تبدیل iterator نوع push به next()/stop() برای zip.
// Package iterator shows Iterator with Go 1.23 range-over-func: iter.Seq for
// a tree walk, iter.Seq2 for a paginated API that can fail, iter.Pull for a
// caller that wants to pull values one at a time.
package iterator
import (
"context"
"iter"
)
// Category is a tree; callers should not care that it is a tree.
type Category struct {
Name string
Children []*Category
}
// All yields every category depth-first. Returning false from yield stops early.
func (c *Category) All() iter.Seq[*Category] {
return func(yield func(*Category) bool) {
c.walk(yield)
}
}
func (c *Category) walk(yield func(*Category) bool) bool {
if !yield(c) {
return false
}
for _, ch := range c.Children {
if !ch.walk(yield) {
return false
}
}
return true
}
// Page is what a paginated API returns.
type Page struct {
IDs []int
Cursor string // empty when there is no next page
}
// FetchFunc loads one page; in production it is an HTTP or SQL call.
type FetchFunc func(ctx context.Context, cursor string) (Page, error)
// Each hides pagination: the caller ranges over ids and sees errors inline.
func Each(ctx context.Context, fetch FetchFunc) iter.Seq2[int, error] {
return func(yield func(int, error) bool) {
cursor := ""
for {
p, err := fetch(ctx, cursor)
if err != nil {
yield(0, err)
return
}
for _, id := range p.IDs {
if !yield(id, nil) {
return
}
}
if p.Cursor == "" {
return
}
cursor = p.Cursor
}
}
}
// Zip merges two sequences pairwise using pull iterators.
func Zip[A, B any](as iter.Seq[A], bs iter.Seq[B]) iter.Seq2[A, B] {
return func(yield func(A, B) bool) {
nextA, stopA := iter.Pull(as)
defer stopA()
nextB, stopB := iter.Pull(bs)
defer stopB()
for {
a, okA := nextA()
b, okB := nextB()
if !okA || !okB || !yield(a, b) {
return
}
}
}
}Laravel: یک generator پشت IteratorAggregate، و LazyCollection::make دور یک API صفحهبندیشده. مستندات Laravel: «the LazyCollection class leverages PHP's generators to allow you to work with very large datasets while keeping memory usage low.» متدهای lazy() (کوئریهای chunkشده) و cursor() (یک کوئری، هر بار یک model) در Eloquent iteratorهایی روی جدولاند.
<?php
// Iterator in PHP/Laravel: generators, IteratorAggregate, and LazyCollection,
// which wraps a generator so you can stream rows or API pages with low memory.
namespace App\Catalog;
use Generator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\LazyCollection;
use IteratorAggregate;
use Traversable;
/** A collection type that hides its storage: callers just foreach it. */
final class CategoryTree implements IteratorAggregate
{
/** @param list<CategoryTree> $children */
public function __construct(public readonly string $name, private array $children = []) {}
public function getIterator(): Traversable
{
return $this->walk();
}
private function walk(): Generator
{
yield $this;
foreach ($this->children as $child) {
yield from $child->walk();
}
}
}
final class SupplierCatalog
{
/** Hides cursor pagination: the caller sees one lazy stream of products. */
public function products(): LazyCollection
{
return LazyCollection::make(function () {
$cursor = null;
do {
$page = Http::get('https://supplier.example/api/products', ['cursor' => $cursor])->throw()->json();
foreach ($page['data'] as $product) {
yield $product;
}
$cursor = $page['next_cursor'] ?? null;
} while ($cursor !== null);
});
}
}
// Usage: only as many pages are fetched as take() needs.
// $cheap = app(SupplierCatalog::class)->products()
// ->filter(fn ($p) => $p['price'] < 1000)
// ->take(50)
// ->all();
//
// Eloquent iterators over large tables:
// foreach (Order::where('status', 'paid')->lazy() as $order) { ... } // chunked queries
// foreach (Order::cursor() as $order) { ... } // one query, one row hydrated at a timeپیامدها: فراخواننده از نحوهٔ ذخیره مستقل است؛ حافظه ثابت میماند؛ توقف زودهنگام مجانی است. هزینه: iterator تنبل منابع را (cursor باز، صفحهٔ HTTP) تا وقتی فراخواننده کند است نگه میدارد؛ خطا وسط حلقه ظاهر میشود نه از اول؛ دوبار پیمایش ممکن است کار را دوباره اجرا کند (remember() در Laravel مقدارهای شمردهشده را cache میکند).
کی استفاده نکنیم: مجموعههای کوچک در حافظه که slice یا آرایه سادهتر و سریعتر است.
مرتبط / اشتباهگرفته با: Iterator ترتیب را تعیین میکند، Visitor عملیات هر نوع را؛ درختهای Composite معمولاً با iterator پیمایش میشوند (Structural Patterns). شکل توزیعشده: صفحهبندی cursor یا keyset روی API (Pagination)، و مصرفکنندهای که partition یک stream را offset به offset میخواند.
تست: دنباله، توقف زودهنگام (break بعد از N)، و yield شدن خطاها را بررسی کنید (iterator_test.go).
Mediator مهم
"Mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object." — refactoring.guru، Mediator
به زبان ساده: هواپیماها با هم حرف نمیزنند، با برج حرف میزنند. قواعد مال برج است.
بدفهمی رایج: «event bus یک Mediator است، پس هر event busی coupling را درست میکند.» یک bus عمومی فقط مسیریابی میکند؛ قواعد coupling همچنان در listenerهاست. Mediator به معنای GoF منطق هماهنگی را در خودش دارد. اگر قواعد «چه کسی به چه کسی واکنش نشان میدهد» در بیست listener پخش است، Observer دارید، نه Mediator.
تعریف و اجزا: interface میانجی (Mediator)؛ یک میانجی مشخص که همهٔ همکاران (Colleagues) را میشناسد و نحوهٔ تعاملشان را رمزگذاری میکند؛ همکارانی که فقط میانجی را میشناسند. با n همکار، پیوندهای مستقیم n(n−1)/2 میشوند؛ با میانجی n.
Colleague Mediator (Checkout) Effect
1 Coupon applied -> Changed("coupon") recalculate()
2 total 6000 -> 4800 (below 5000) shipping 0 -> 500
3 Summary.Payable = 5300 Cart, Coupon, Summary never call each otherسناریوی واقعی: فرم checkout که coupon و کشور و سبد روی هم اثر میگذارند؛ اتاق چت؛ تخصیص منابع به سبک برج مراقبت؛ هماهنگکنندهٔ ماژول در modular monolith (یک use case که inventory و billing و notifications را به ترتیب صدا میزند)؛ دیالوگهای UI با فیلدهای وابسته.
Go: یک struct هماهنگکننده؛ و شکل goroutine که در آن یک goroutine مالک state است و همکاران از طریق channel به آن فرمان میفرستند (بدون قفل، همهٔ قواعد در یک حلقه).
// Package mediator shows Mediator: colleagues never call each other; they
// tell the mediator what happened and it decides who reacts.
package mediator
// Colleagues of a checkout form.
type Cart struct{ Total int64 }
type Coupon struct {
Code string
Percent int64
}
type ShippingForm struct{ Country string }
type Summary struct{ Payable, Shipping int64 }
// Checkout is the mediator. Every interaction rule lives here, not in the parts.
type Checkout struct {
Cart *Cart
Coupon *Coupon
Shipping *ShippingForm
Summary *Summary
}
// Changed is the single entry point colleagues use.
func (m *Checkout) Changed(source string) {
switch source {
case "cart", "coupon", "country":
m.recalculate()
}
}
func (m *Checkout) recalculate() {
total := m.Cart.Total
if m.Coupon != nil && m.Coupon.Code != "" {
total -= total * m.Coupon.Percent / 100
}
var ship int64
switch {
case m.Shipping.Country != "DE":
ship = 1_500 // international
case total < 5_000:
ship = 500 // domestic, below the free-shipping threshold
}
m.Summary.Shipping = ship
m.Summary.Payable = total + ship
}
// Command is what goroutine colleagues send to a channel-based mediator.
type Command struct {
Source string
Apply func(*Checkout)
Done chan Summary
}
// Run owns the Checkout; only this goroutine touches it, so no locks.
func Run(m *Checkout, in <-chan Command) {
for c := range in {
c.Apply(m)
m.Changed(c.Source)
c.Done <- *m.Summary
}
}Laravel: یک کلاس هماهنگکننده (Action) که تعامل بین ماژولها را در اختیار دارد؛ event dispatcher میانجی عمومی بین ناشران و listenerهاست.
<?php
// Mediator: modules do not call each other; a coordinator owns the interaction.
// Laravel's event dispatcher is a generic mediator between publishers and listeners.
namespace App\Checkout;
use App\Billing\BillingModule;
use App\Inventory\InventoryModule;
use App\Notifications\NotificationModule;
use Illuminate\Support\Facades\DB;
/**
* Without a mediator, Inventory calls Billing which calls Notifications:
* every module knows two others. Here each module knows only the mediator's
* call into it, and the order of interaction is in one readable place.
*/
final class CheckoutMediator
{
public function __construct(
private readonly InventoryModule $inventory,
private readonly BillingModule $billing,
private readonly NotificationModule $notifications,
) {}
public function placeOrder(int $customerId, array $lines): int
{
return DB::transaction(function () use ($customerId, $lines) {
$reservationId = $this->inventory->reserve($lines);
$orderId = $this->billing->createInvoice($customerId, $lines, $reservationId);
$this->notifications->orderPlaced($customerId, $orderId); // queued inside the module
return $orderId;
});
}
}
// The dispatcher as mediator: a module announces, it does not address anyone.
// event(new \App\Events\OrderPlaced($orderId));
// Event::listen(\App\Events\OrderPlaced::class, [\App\Inventory\Listeners\Commit::class, 'handle']);پیامدها: همکاران ساده و قابل استفادهٔ دوباره میشوند؛ تعامل در یک جا خواناست. هزینه: میانجی ممکن است به god object تبدیل شود (برای هر use case جدا کنید)؛ همه به آن وابستهاند.
کی استفاده نکنیم: دو سه همکار با یک تعامل؛ یا وقتی اعلانهایی با واکنشهای مستقل کافی است (Observer).
شکل توزیعشده: orchestration در saga یک میانجی بین سرویسهاست؛ در اصطلاح EIP یک Process Manager.
مرتبط / اشتباهگرفته با: Observer و pub/sub و Mediator؛ Facade دسترسی به یک زیرسیستم را ساده میکند، Mediator همتاها را هماهنگ میکند (Structural Patterns).
تست: همکاران را از طریق میانجی به حرکت درآورید و حالت نهایی را بررسی کنید؛ برای شکل channel فرمان بفرستید و پاسخ بخوانید، بدون sleep (checkout_test.go).
Memento تکمیلی
"Memento is a behavioral design pattern that lets you save and restore the previous state of an object without revealing the details of its implementation." — refactoring.guru، Memento
به زبان ساده: یک snapshot مهرومومشده بگیرید که بعداً بتوانید برای بازگردانی پس بدهید، بدون اینکه کس دیگری محتوایش را بخواند.
بدفهمی رایج: «Memento یعنی serialize کردن object به JSON.» serialize کردن سازوکار است. الگو دربارهٔ این است که چه کسی اجازهٔ خواندن snapshot را دارد: فقط سازنده (Originator). نگهدارنده (Caretaker) مثل پشتهٔ undo یا جدول نسخهها آن را ذخیره میکند اما نباید به فیلدهایش وابسته باشد تا جزئیات داخلی سازنده بتواند عوض شود.
تعریف و اجزا: یک سازنده (Originator) که memento میسازد و از آن بازمیگردد؛ یک یادگاری (Memento)، یعنی state مات بهعلاوهٔ metadata مثل زمان؛ یک نگهدارنده (Caretaker) که mementoها را نگه میدارد (پشته، ring buffer، جدول). refactoring.guru پیوند با Command را یادآوری میکند: «commands are responsible for performing various operations over a target object, while mementos save the state of that object just before a command gets executed.»
User Document (originator) document_versions (caretaker)
1 edit title snapshot() -> v1 {title:A} INSERT v1
2 edit body snapshot() -> v2 {title:B} INSERT v2
3 "restore v1" snapshot() -> v3 (current) INSERT v3 (restore is undoable)
4 fill(v1.state); save() title = A againسناریوی واقعی: undo در ویرایشگرها و صفحههای تنظیمات؛ تاریخچهٔ نسخهٔ سند یا صفحه (ویکی، CMS)؛ نسخهٔ «پیشنویس» در برابر «منتشرشده»؛ نقطهٔ ذخیره در بازی؛ بازگرداندن یک تغییر پیکربندی چندمرحلهای شکستخورده.
Go: فیلدهای unexported باعث میشوند memento بیرون از پکیج مات باشد؛ نگهدارنده محدود است چون حافظه هزینهٔ اصلی است.
// Package memento shows Memento: the originator exports an opaque snapshot,
// a caretaker stores snapshots, and only the originator can read them.
package memento
import "time"
// Settings is the originator. Its fields stay unexported.
type Settings struct {
theme string
fontSize int
}
func (s *Settings) SetTheme(t string) { s.theme = t }
func (s *Settings) SetFontSize(n int) { s.fontSize = n }
func (s *Settings) Theme() string { return s.theme }
func (s *Settings) FontSize() int { return s.fontSize }
// Snapshot is the memento. Outside this package it is opaque: callers can
// store and pass it, but cannot read or change theme or fontSize.
type Snapshot struct {
theme string
fontSize int
At time.Time // metadata is fine to expose
}
func (s *Settings) Save(now time.Time) Snapshot {
return Snapshot{theme: s.theme, fontSize: s.fontSize, At: now}
}
func (s *Settings) Restore(m Snapshot) {
s.theme, s.fontSize = m.theme, m.fontSize
}
// Caretaker keeps a bounded history; it never looks inside a Snapshot.
type Caretaker struct {
Max int
saved []Snapshot
}
func (c *Caretaker) Push(m Snapshot) {
c.saved = append(c.saved, m)
if c.Max > 0 && len(c.saved) > c.Max {
c.saved = c.saved[1:] // drop the oldest: memory is the main cost
}
}
func (c *Caretaker) Pop() (Snapshot, bool) {
if len(c.saved) == 0 {
return Snapshot{}, false
}
m := c.saved[len(c.saved)-1]
c.saved = c.saved[:len(c.saved)-1]
return m, true
}Laravel: snapshotها در جدول نسخهها (schema در سازوکار)؛ خود بازگردانی هم snapshot میشود تا قابل undo باشد.
<?php
// Memento in Laravel: snapshots of a model stored in a versions table.
// The model creates and restores snapshots; the table (caretaker) only stores them.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
class Document extends Model
{
protected $fillable = ['title', 'body', 'settings'];
protected function casts(): array
{
return ['settings' => 'array'];
}
public function versions(): HasMany
{
return $this->hasMany(DocumentVersion::class);
}
/** Originator: decides what goes into the memento. */
public function snapshot(int $userId): DocumentVersion
{
return $this->versions()->create([
'user_id' => $userId,
'version' => ($this->versions()->max('version') ?? 0) + 1,
'state' => $this->only(['title', 'body', 'settings']),
]);
}
/** Originator: the only code that interprets a memento's contents. */
public function restore(DocumentVersion $version, int $userId): void
{
DB::transaction(function () use ($version, $userId) {
$this->snapshot($userId); // restoring is itself undoable
$this->fill($version->state)->save();
});
}
}
class DocumentVersion extends Model
{
public const UPDATED_AT = null; // versions are immutable
protected $fillable = ['user_id', 'version', 'state'];
protected function casts(): array
{
return ['state' => 'array'];
}
}پیامدها: کپسولهسازی (Encapsulation) حفظ میشود؛ undo ساده و محکم. هزینه: حافظه یا فضای ذخیره برای هر snapshot (diff ذخیره کنید یا تاریخچه را محدود کنید)؛ snapshot objectهایی با پیوند بیرونی (فایل، foreign key) ممکن است ناسازگار بازگردانده شود.
کی استفاده نکنیم: objectهای بزرگ که در گامهای ریز ویرایش میشوند (undo با Command یا diff بهتر است)؛ یا وقتی باید بدانید چرا چیزی عوض شد (این یک event log است، Event Sourcing را ببینید).
مرتبط / اشتباهگرفته با: undo با Command یا Memento؛ Prototype (یک کپی) برای objectهای ساده میتواند جای Memento را بگیرد (Creational Patterns). شکل توزیعشده: snapshot در ذخیرهگاه event-sourced.
تست: ذخیره، تغییر، بازگردانی، بررسی برابری؛ بررسی اینکه تاریخچهٔ محدود قدیمیترین را دور میریزد (editor_test.go).
Visitor مهم
"Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate." — refactoring.guru، Visitor
به زبان ساده: مجموعهٔ ثابتی از نوع گره دارید (سطر محصول، سطر ارسال، سطر تخفیف) و مدام عملیات تازه روی آنها اختراع میکنید (مالیات، CSV، PDF). هر عملیات یک کلاس visitor میشود، بهجای یک متد که به همهٔ نوعهای گره اضافه شود.
بدفهمی رایج: «Visitor اضافه کردن هر چیزی را آسان میکند.» اضافه کردن عملیات را آسان و اضافه کردن نوع را سخت میکند: نوع گرهٔ تازه یعنی متد تازه در همهٔ visitorها. این همان مسئلهٔ بیان (Expression Problem) است و Visitor یک طرف آن را انتخاب میکند.
تعریف و اجزا: interface عنصر (Element) با accept(visitor)؛ عناصر مشخص که متد visitor مربوط به نوع خودشان را صدا میزنند (visitor.visitProduct(this))؛ interface بازدیدکننده (Visitor) با یک متد برای هر نوع عنصر؛ visitorهای مشخص برای هر عملیات. این دو فراخوانی (accept عنصر را انتخاب میکند، visitX عملیات را) ارسال دوگانه (Double Dispatch) هستند؛ refactoring.guru: «It uses a technique called Double Dispatch, which helps to execute the proper method on an object without cumbersome conditionals.»
Apply(items, vat)
1 ProductLine.accept(vat) -> vat.visitProduct(p) tax += 190
2 ShippingLine.accept(vat) -> vat.visitShipping(s) tax += 95
3 DiscountLine.accept(vat) -> vat.visitDiscount(d) tax -= 19 => 266
4 same items, Lines visitor -> three CSV rows, items unchangedسناریوی واقعی: کامپایلرها و linterها که روی AST راه میروند (go/ast در Go، node visitorهای PHP-Parser، قواعد ESLint)؛ export یک مدل سند به چند فرمت؛ محاسبهٔ metric روی یک درخت دامنهٔ ثابت؛ مالیات و گزارش روی سطرهای فاکتور.
Go: double dispatch کلاسیک، و Visitor خود stdlib. مستندات Go: «A Visitor's Visit method is invoked for each node encountered by Walk»؛ ast.Inspect همان پیمایش با یک closure است، و Go 1.23 تابع ast.Preorder را اضافه کرد که «returns an iterator over all the nodes of the syntax tree».
// Package visitor shows Visitor two ways: classic double dispatch over a
// closed set of line-item types, and the stdlib's go/ast Walk and Inspect.
package visitor
import (
"go/ast"
"go/parser"
"go/token"
)
// Item is the element interface: every item accepts a visitor.
type Item interface{ Accept(v Visitor) }
type Product struct {
SKU string
Cents int64
}
type Shipping struct{ Cents int64 }
type Discount struct{ Cents int64 }
// Double dispatch: the item picks the visitor method by its own type.
func (p Product) Accept(v Visitor) { v.VisitProduct(p) }
func (s Shipping) Accept(v Visitor) { v.VisitShipping(s) }
func (d Discount) Accept(v Visitor) { v.VisitDiscount(d) }
// Visitor is one operation over all item types. New operation = new visitor;
// new item type = edit every visitor (the trade-off).
type Visitor interface {
VisitProduct(Product)
VisitShipping(Shipping)
VisitDiscount(Discount)
}
// VAT computes tax: products 19%, shipping 19%, discounts reduce the base.
type VAT struct{ Cents int64 }
func (t *VAT) VisitProduct(p Product) { t.Cents += p.Cents * 19 / 100 }
func (t *VAT) VisitShipping(s Shipping) { t.Cents += s.Cents * 19 / 100 }
func (t *VAT) VisitDiscount(d Discount) { t.Cents -= d.Cents * 19 / 100 }
// Lines renders an invoice: a second operation, no change to the items.
type Lines struct{ Out []string }
func (l *Lines) VisitProduct(p Product) { l.Out = append(l.Out, "product "+p.SKU) }
func (l *Lines) VisitShipping(Shipping) { l.Out = append(l.Out, "shipping") }
func (l *Lines) VisitDiscount(Discount) { l.Out = append(l.Out, "discount") }
func Apply(items []Item, v Visitor) {
for _, it := range items {
it.Accept(v)
}
}
// CountFuncs uses ast.Inspect: a visitor written as a closure.
func CountFuncs(src string) (int, error) {
f, err := parser.ParseFile(token.NewFileSet(), "x.go", src, 0)
if err != nil {
return 0, err
}
n := 0
ast.Inspect(f, func(node ast.Node) bool {
if _, ok := node.(*ast.FuncDecl); ok {
n++
}
return true // keep descending
})
return n, nil
}
// callCounter implements ast.Visitor for ast.Walk.
type callCounter struct{ calls map[string]int }
func (c callCounter) Visit(node ast.Node) ast.Visitor {
if call, ok := node.(*ast.CallExpr); ok {
if id, ok := call.Fun.(*ast.Ident); ok {
c.calls[id.Name]++
}
}
return c
}
// CountCalls returns how often each plain function name is called.
func CountCalls(src string) (map[string]int, error) {
f, err := parser.ParseFile(token.NewFileSet(), "x.go", src, 0)
if err != nil {
return nil, err
}
c := callCounter{calls: map[string]int{}}
ast.Walk(c, f)
return c.calls, nil
}Laravel / PHP: double dispatch روی کلاسهای readonly سطر؛ match (true) با instanceof جایگزین سبکتر برای مجموعههای بستهٔ کوچک است.
<?php
// Visitor in PHP: double dispatch over a closed set of invoice line types.
// Adding an operation = a new visitor class; adding a line type = edit all visitors.
namespace App\Invoicing;
interface LineVisitor
{
public function visitProduct(ProductLine $line): void;
public function visitShipping(ShippingLine $line): void;
public function visitDiscount(DiscountLine $line): void;
}
interface Line
{
public function accept(LineVisitor $visitor): void;
}
final readonly class ProductLine implements Line
{
public function __construct(public string $sku, public int $cents) {}
public function accept(LineVisitor $visitor): void { $visitor->visitProduct($this); }
}
final readonly class ShippingLine implements Line
{
public function __construct(public int $cents) {}
public function accept(LineVisitor $visitor): void { $visitor->visitShipping($this); }
}
final readonly class DiscountLine implements Line
{
public function __construct(public int $cents) {}
public function accept(LineVisitor $visitor): void { $visitor->visitDiscount($this); }
}
final class VatVisitor implements LineVisitor
{
public int $cents = 0;
public function visitProduct(ProductLine $line): void { $this->cents += intdiv($line->cents * 19, 100); }
public function visitShipping(ShippingLine $line): void { $this->cents += intdiv($line->cents * 19, 100); }
public function visitDiscount(DiscountLine $line): void { $this->cents -= intdiv($line->cents * 19, 100); }
}
final class CsvRowsVisitor implements LineVisitor
{
/** @var list<array> */
public array $rows = [];
public function visitProduct(ProductLine $line): void { $this->rows[] = ['product', $line->sku, $line->cents]; }
public function visitShipping(ShippingLine $line): void { $this->rows[] = ['shipping', '', $line->cents]; }
public function visitDiscount(DiscountLine $line): void { $this->rows[] = ['discount', '', -$line->cents]; }
}
// PHP 8 alternative when the set of types is closed and small: a match on the class.
// $vat = fn (Line $l) => match (true) {
// $l instanceof ProductLine, $l instanceof ShippingLine => intdiv($l->cents * 19, 100),
// $l instanceof DiscountLine => -intdiv($l->cents * 19, 100),
// };پیامدها: عملیات تازه بدون دست زدن به کلاسهای عنصر؛ رفتار مرتبط در هر visitor جمع میشود. هزینه: نوع عنصر تازه به همهٔ visitorها دست میزند؛ visitorها اغلب به جزئیات داخلی عنصر نیاز دارند (فیلد public یا getter)؛ واسطهٔ accept/visit خواننده را گیج میکند. در Go یک type switch (switch n := node.(type)) اغلب روشنتر است.
کی استفاده نکنیم: نوعهای عنصر زیاد عوض میشوند؛ فقط یکی دو عملیات وجود دارد.
مرتبط / اشتباهگرفته با: Iterator (ترتیب) در برابر Visitor (عملیات)؛ type switch جایگزین سبک است (ارسال یگانه و دوگانه). شکل توزیعشده ندارد: بین سرویسها هر مصرفکننده رسیدگی به هر نوع event را خودش پیاده میکند.
تست: هر visitor را روی فهرست ثابتی از عناصر اجرا کنید و نتیجه را بررسی کنید؛ برای go/ast یک رشتهٔ کد کوچک parse کنید و شمارشها را بررسی کنید (visitor_test.go).
Interpreter تکمیلی
به زبان ساده: برای یک زبان کوچک (قواعد تخفیف، فیلتر جستوجو، شرط feature flag) برای هر قاعدهٔ گرامر یک کلاس بسازید، از جمله یک درخت بسازید و درخت را ارزیابی کنید.
بدفهمی رایج: «Interpreter راه ساختن زبان برنامهنویسی است.» برای هر چیزی فراتر از یک گرامر کوچک از parser generator یا یک موتور عبارت واقعی استفاده میکنید. Interpreter در GoF برای گرامرهای کوچک و پایدار است که درختی از objectها به اندازهٔ کافی روشن است. Wikipedia ساختار را خلاصه میکند: «Represent a sentence in the language by an abstract syntax tree (AST) made up of Expression instances» و یادآوری میکند که درخت یک Composite است.
تعریف و اجزا: عبارت انتزاعی (Abstract Expression) با Eval/evaluate؛ عبارتهای پایانی (Terminal Expressions) مثل مقایسه و literal؛ عبارتهای ناپایانی (Nonterminal Expressions) مثل and و or که زیرعبارت دارند؛ یک زمینه (factها)؛ یک client یا parser که درخت را میسازد. Visitor راه معمول برای افزودن عملیات دیگر بهجز ارزیابی است (چاپ زیبا، اعتبارسنجی).
Rule JSON: all[ total>=10000, any[ tier==gold, orders>=20 ] ]
1 RuleParser::parse -> AllOf(AtLeast, AnyOf(Equals, AtLeast))
2 evaluate({total:12000, tier:gold}) -> AtLeast true -> AnyOf: Equals true -> true
3 admin edits the JSON in a UI; no deploy needed for a new ruleسناریوی واقعی: قواعد تبلیغ و قیمتگذاری که کاربران کسبوکار ویرایش میکنند؛ قواعد دسترسی (شرطهای مبتنی بر attribute)؛ DSL فیلتر جستوجو؛ شرطهای هشدار.
// Package interpreter shows Interpreter: a tiny rule language for discounts.
// Each grammar rule is a type; the sentence is a tree; Eval interprets it.
//
// expr := cmp | expr "and" expr | expr "or" expr
// cmp := field (">=" | "==") value
package interpreter
// Facts are the input the rules are evaluated against.
type Facts map[string]int64
// Expr is the abstract expression.
type Expr interface{ Eval(f Facts) bool }
// Terminal expressions.
type AtLeast struct {
Field string
Min int64
}
func (e AtLeast) Eval(f Facts) bool { return f[e.Field] >= e.Min }
type Equals struct {
Field string
Want int64
}
func (e Equals) Eval(f Facts) bool { return f[e.Field] == e.Want }
// Nonterminal expressions: they hold sub-expressions (a Composite).
type And struct{ L, R Expr }
func (e And) Eval(f Facts) bool { return e.L.Eval(f) && e.R.Eval(f) }
type Or struct{ L, R Expr }
func (e Or) Eval(f Facts) bool { return e.L.Eval(f) || e.R.Eval(f) }
// VIPRule is the sentence: total >= 10000 and (tier == 2 or orders >= 20).
var VIPRule Expr = And{
L: AtLeast{"total", 10_000},
R: Or{Equals{"tier", 2}, AtLeast{"orders", 20}},
}<?php
// Interpreter: a tiny discount-rule language stored as JSON and evaluated
// as a tree of expression objects (each grammar rule is a class).
namespace App\Rules;
use InvalidArgumentException;
interface Expr
{
public function evaluate(array $facts): bool;
}
final readonly class AtLeast implements Expr
{
public function __construct(private string $field, private int $min) {}
public function evaluate(array $facts): bool { return ($facts[$this->field] ?? 0) >= $this->min; }
}
final readonly class Equals implements Expr
{
public function __construct(private string $field, private int|string $value) {}
public function evaluate(array $facts): bool { return ($facts[$this->field] ?? null) === $this->value; }
}
final readonly class AllOf implements Expr
{
/** @param list<Expr> $parts */
public function __construct(private array $parts) {}
public function evaluate(array $facts): bool
{
foreach ($this->parts as $p) {
if (! $p->evaluate($facts)) {
return false;
}
}
return true;
}
}
final readonly class AnyOf implements Expr
{
/** @param list<Expr> $parts */
public function __construct(private array $parts) {}
public function evaluate(array $facts): bool
{
foreach ($this->parts as $p) {
if ($p->evaluate($facts)) {
return true;
}
}
return false;
}
}
/** Parser: JSON stored by an admin UI -> expression tree. */
final class RuleParser
{
public static function parse(array $node): Expr
{
return match ($node['op']) {
'gte' => new AtLeast($node['field'], (int) $node['value']),
'eq' => new Equals($node['field'], $node['value']),
'all' => new AllOf(array_map(self::parse(...), $node['of'])),
'any' => new AnyOf(array_map(self::parse(...), $node['of'])),
default => throw new InvalidArgumentException("Unknown op {$node['op']}"),
};
}
}
// RuleParser::parse(['op' => 'all', 'of' => [
// ['op' => 'gte', 'field' => 'total', 'value' => 10000],
// ['op' => 'any', 'of' => [['op' => 'eq', 'field' => 'tier', 'value' => 'gold'], ['op' => 'gte', 'field' => 'orders', 'value' => 20]]],
// ]])->evaluate(['total' => 12000, 'tier' => 'gold']); // trueکی استفاده نکنیم: گرامرهای بزرگ، ارزیابی حساس به کارایی، یا وقتی یک موتور موجود (WHERE در SQL، CEL، JSON Logic، کوئری موتور جستوجو) آن را پوشش میدهد. قواعد را به شکل داده ذخیره کنید، هنگام ذخیره اعتبارسنجی کنید و نسخهگذاری کنید.
مرتبط / اشتباهگرفته با: درخت یک Composite است (Structural Patterns)؛ Visitor به آن عملیات اضافه میکند. تست: جدول درستی factها → نتیجهٔ مورد انتظار برای هر قاعده (rules_test.go).
نگاه هر زبان
کدام قابلیت توکار خودش همان الگوست، تا دوباره پیادهاش نکنید.
| الگو | stdlib / idiom در Go | PHP / Laravel 13 | Java / Spring | JavaScript / TypeScript |
|---|---|---|---|---|
| Template Method | تابع + interface مرحلهها | abstract class، متد final؛ setUp در PHPUnit | AbstractController، callbackهای JdbcTemplate | کلاس پایه یا تابع مرتبهبالا |
| Chain of Responsibility | func(http.Handler) http.Handler | middleware، facade Pipeline | زنجیرهٔ Filter در Servlet، filter chain در Spring Security | middleware در Express/Koa |
| State | interface برای هر وضعیت یا map گذار | backed enum + enum cast در Eloquent | Spring Statemachine | XState |
| Command | مقدار با Do/Undo؛ closure | Job (ShouldQueue)، Bus::chain، دستور Artisan، scheduler | Runnable، @Async | actionهای Redux |
| Observer | callback، channel؛ context.AfterFunc | event/listener، Eloquent observer | ApplicationEventPublisher، @EventListener | EventTarget، RxJS |
| Strategy | مقدار func، sort.Interface، slices.SortFunc | interface + binding؛ tag/tagged در container؛ Gate و Policy | interface + @Qualifier | تابع بهعنوان مقدار |
| Iterator | iter.Seq، iter.Seq2، iter.Pull | Iterator، IteratorAggregate، generator، LazyCollection | Iterator، Stream | Symbol.iterator، generator |
| Mediator | struct هماهنگکننده؛ goroutine مالک state | Action/هماهنگکننده؛ event dispatcher | کتابخانههای سبک MediatR مال .NETاند؛ Spring از service استفاده میکند | store در Redux بهعنوان میانجی |
| Memento | struct با فیلدهای unexported | جدول نسخهها، کپی با $model->replicate() | snapshot قابل serialize | snapshotهای state تغییرناپذیر |
| Visitor | ast.Walk، ast.Inspect، ast.Preorder، type switch | accept/visit، NodeVisitor در PHP-Parser | FileVisitor (Files.walkFileTree) | visitorهای Babel/ESLint |
| Interpreter | interface Expr؛ text/template/parse درخت میسازد | کلاسهای قاعده؛ Blade کامپایل میکند، تفسیر نمیکند | SpEL | JSON Logic |
context.Context در Go همزمان دو الگوست. channel Done() یک قلاب observer است («Done returns a channel that's closed when work done on behalf of this context should be canceled»، مستندات Go) و لغو (Cancellation) در زنجیرهای از contextهای مشتق پایین میرود؛ context.AfterFunc «arranges to call f in its own goroutine after ctx is canceled» که یک observer ثبتشده است.
Macroable در Laravel الگوی رفتاری نیست. Collection::macro('toUpper', fn ...) در زمان اجرا متد اضافه میکند («Collections are "macroable"»، مستندات Laravel). این یک سازوکار توسعه است (نزدیک به ایدهٔ بعدی GoF یعنی extension object)؛ برای helperهای کوچک از آن استفاده کنید، نه برای تزریق رفتار برای هر درخواست، که کار Strategy است.
سازوکار
ارسال یگانه و دوگانه (Single vs Double Dispatch) مهم
Go و PHP و Java متد اجرایی را فقط با نوع زمان اجرای گیرنده انتخاب میکنند (ارسال یگانه). vat.visit(item) نمیتواند بر اساس نوع زمان اجرای آرگومان بین visitProduct و visitShipping انتخاب کند؛ overloadها (هرجا باشند) در زمان کامپایل انتخاب میشوند. Visitor ارسال دوم را اضافه میکند: item.accept(v) روی عنصر dispatch میشود و بعد v.visitProduct(this) را صدا میزند که روی visitor dispatch میشود. جایگزینها: type switch در Go، match (true) با instanceof در PHP؛ هر دو برای مجموعههای بسته و کوچک خوباند و بررسی زمان کامپایل «هر visitor همهٔ نوعها را پوشش میدهد» را از دست میدهند.
iterator نوع push و pull حیاتی
| سبک | چه کسی حلقه را کنترل میکند | Go | PHP | کاربرد معمول |
|---|---|---|---|---|
| Push | iterator شما را صدا میزند | iter.Seq[V]: func(yield func(V) bool) | foreach روی generator (شبیه pull، اجرا به شکل coroutine) | حلقهٔ range، streaming |
| Pull | شما next() را صدا میزنید | iter.Pull(seq) جفت next, stop برمیگرداند | Iterator::current()/next()/valid() | zip، merge، parser |
| Channel | goroutine تولیدکننده میفرستد | chan T + goroutine | ندارد | تولیدکنندهٔ همزمان؛ هزینهٔ یک goroutine و نیاز به لغو |
مستندات Go: «The standard iterators can be thought of as “push iterators”»؛ Pull «converts a standard push iterator to a “pull iterator”». همیشه stop را صدا بزنید (با defer)، وگرنه state داخلی iterator نشت میکند. iterator نوع push باید به false برگشتن از yield احترام بگذارد؛ نادیده گرفتنش وقتی حلقه تمام شده در زمان اجرا panic میدهد.
اعلان همزمان و صفشده حیاتی
| سؤال | observer همزمان | listener صفشده (ShouldQueue) | pub/sub با broker |
|---|---|---|---|
| اجرا در | thread/درخواست subject | queue worker | سرویس مصرفکننده |
| subject منتظر میماند | بله | نه (فقط push) | نه |
| observer خطا پرتاب کند | exception به subject میرسد | worker retry میکند، سپس failed_jobs | retry، سپس DLQ |
| همان تراکنش دیتابیس | بله (با هم rollback میشوند) | نه | نه |
| از crash جان به در میبرد | نه | بله، پس از push | بله، پس از acknowledge |
| ترتیب | ترتیب ثبت | در هر صف، بین workerها تضمینشده نیست | در هر partition/صف |
دو تله: dispatch درون تراکنشی که بعداً rollback میشود (راهحل: ShouldDispatchAfterCommit روی event، یا ثبت eventها روی aggregate و انتشار پس از commit مثل آزمایشگاه Go)؛ و observerی که همزمان کل دنیا را بار میکند (به صف ببریدش).
پشتههای undo: Command یا Memento مهم
| undo با Command | undo با Memento | |
|---|---|---|
| چه ذخیره میکند | راه برگشت (عمل معکوس + حداقل مقدار قبلی) | snapshot کامل (یا diff) پیش از تغییر |
| حافظه | کم | برای objectهای بزرگ زیاد |
| برای چه کار میکند | عملیات برگشتپذیر | هر تغییری، حتی پیچیده |
| کجا شکست میخورد | اثرهای جانبی بیرون از کنترل (ایمیل، پرداخت) | پیوندهای بیرونی (فایل، جدولهای دیگر) |
| Redo | اجرای دوبارهٔ فرمان | snapshot «بعد» را هم نگه دارید |
قواعد هر دو: عمل تازه پشتهٔ redo را پاک میکند؛ تاریخچه را محدود کنید (تعداد یا بایت)؛ فقط آنچه لازم است را پایدار کنید. شکلهای پایدار:
-- PostgreSQL: command history as an audit log (Command)
CREATE TABLE command_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
document_id bigint NOT NULL REFERENCES documents(id),
user_id bigint NOT NULL,
command text NOT NULL, -- e.g. App\Editing\RenameDocument
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON command_log (document_id, id);
-- Snapshots (Memento): one row per version, immutable
CREATE TABLE document_versions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
document_id bigint NOT NULL REFERENCES documents(id),
version int NOT NULL,
user_id bigint NOT NULL,
state jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (document_id, version)
);قید UNIQUE (document_id, version) دو snapshot همزمان را که هر دو max(version) + 1 یکسان حساب کردهاند به خطای نقض یکتایی (Unique Violation) تبدیل میکند (SQLSTATE 23505 در PostgreSQL، خطای 1062 در MySQL) بهجای تکرار بیصدا؛ روی آن retry کنید.
جدول transition و state machine پایدار حیاتی
الگوی State در حافظه کافی نیست وقتی دو پردازه میتوانند به یک سفارش دست بزنند. دیتابیس باید همان ماشین را اعمال کند:
-- PostgreSQL: allowed transitions as data, checked by the UPDATE below
CREATE TABLE order_transitions (
from_status text NOT NULL,
to_status text NOT NULL,
PRIMARY KEY (from_status, to_status)
);
INSERT INTO order_transitions VALUES
('pending','paid'), ('pending','cancelled'),
('paid','shipped'), ('paid','refunded'), ('shipped','delivered');
ALTER TABLE orders ADD CONSTRAINT orders_status_check
CHECK (status IN ('pending','paid','shipped','delivered','cancelled','refunded'));
-- Compare-and-set transition: succeeds for exactly one concurrent caller
UPDATE orders SET status = 'paid', updated_at = now()
WHERE id = 42 AND status = 'pending'
AND EXISTS (SELECT 1 FROM order_transitions WHERE from_status = 'pending' AND to_status = 'paid');
-- 1 row: you won. 0 rows: someone else moved it, or the move is illegal.
-- History table written by the transition (Observer in SQL form)
CREATE TABLE order_status_history (
order_id bigint NOT NULL, from_status text NOT NULL, to_status text NOT NULL,
changed_at timestamptz NOT NULL DEFAULT now()
);UPDATE ... WHERE status = 'pending' شرطی، همزمانی خوشبینانه (Optimistic Concurrency) روی خود وضعیت است؛ Optimistic vs Pessimistic Locking را ببینید. MySQL InnoDB هم برای این دستور همین رفتار را دارد (قفل سطری که اولین UPDATE میگیرد باعث میشود دومی پس از commit اولی شرط را دوباره بررسی کند). قید CHECK در PostgreSQL و در MySQL از نسخهٔ 8.0.16 اعمال میشود.
ترتیب middleware: پیاز مهم
Chain(final, Logging, RequireToken, RateLimit)
1 Logging before -> calls next
2 RequireToken before -> calls next
3 RateLimit before -> calls next
4 final handler
5 RateLimit after
6 RequireToken after
7 Logging after (sees status code, duration)اولین middleware فهرست بیرونیترین لایه است: در مسیر ورود اول و در مسیر خروج آخر اجرا میشود. در Go کمکی Chain پیاز را با پیچیدن از انتها میسازد؛ در Laravel ترتیب همان ترتیب آرایهٔ middleware است (و stack سراسری بیرون از middleware مسیر). recovery و tracing را بیرونیترین بگذارید، auth را پیش از هر چیزی که به داده دست میزند، و rate limiting را پیش از کار پرهزینه.
Pipeline و middleware در Laravel تکمیلی
Pipeline::send($input)->through([...])->then($destination) هر objectی را از کلاسهای invokable یا closureها عبور میدهد؛ هر کدام ورودی و $next را میگیرد. نام کلاسها از طریق container resolve میشوند («If a class name is provided, the class will be instantiated via Laravel's service container»، مستندات Laravel)، پس pipeها وابستگی injectشده دارند. thenReturn() ورودی را پس از آخرین pipe برمیگرداند. از آن برای مرحلههای checkout، مرحلههای import و فیلترهای کوئری استفاده کنید؛ دغدغههای HTTP را در middleware نگه دارید.
تست هر الگو
| الگو | چه چیزی را بررسی کنیم | ابزار Go | ابزار Laravel |
|---|---|---|---|
| Template Method | ترتیب مرحلهها؛ خروجی هر نسخه | Steps جعلی، strings.Builder | unit test ساده روی زیرکلاس |
| Chain | جایی که باید متوقف میشود؛ ترتیب؛ next یکبار صدا زده شود | httptest.NewRecorder، next جعلی | feature test با $this->get()؛ صدا زدن handle با closure |
| State | همهٔ گذارهای مجاز و غیرمجاز؛ گذار همزمان | تست جدولی روی جفتها | unit test روی enum؛ تست DB برای update شرطی |
| Command | do و بعد undo برمیگرداند؛ serialization؛ idempotency | گیرندهٔ جعلی | Queue::fake()، Bus::fake()، Bus::assertChained |
| Observer | dispatch شد یا نه؛ اثر listener بهتنهایی | callback ضبطکننده | Event::fake()، Event::assertDispatched، assertNotDispatched |
| Strategy | قرارداد یکسان برای هر پیادهسازی | جدولمحور، یک سطر برای هر strategy | data provider روی سرویسهای tagشده |
| Iterator | دنباله، توقف زودهنگام، خطا وسط stream | slices.Collect، break در حلقه | LazyCollection با HTTP جعلی (Http::fake) |
| Mediator | حالت نهایی پس از رویدادهای همکاران | درخواست/پاسخ با channel، بدون sleep | mock ماژولها، بررسی ترتیب فراخوانی |
| Memento | بازگردانی برابر ذخیره؛ تاریخچهٔ محدود | فیلدهای unexported با getter مقایسه میشوند | تست DB روی جدول نسخهها |
| Visitor | هر visitor روی فهرست ثابت عناصر | parse رشتهٔ کد برای go/ast | unit test برای هر visitor |
| Interpreter | جدول درستی قاعده | تست جدولی factها | تست parser + evaluate |
مجموعهتست Go را با race detector اجرا کنید: go test -race ./... از مسیر docs/snippets/design/behavioral-patterns/go (هر یازده پکیج و آزمایشگاه پاس میشوند).
حل مسئلههای کلاسیک
| مسئله | الگو(ها) | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
ifهای وضعیت سفارش همهجا | State (+ جدول transition) | enum/نوع وضعیت مالک گذارها؛ UPDATE شرطی | قواعد در یک جا؛ وضعیت غیرمجاز نداریم | جدول و کد باید هماهنگ بمانند |
| controller چاق checkout | Chain (Pipeline) + Command | یک pipe برای هر مرحله؛ یک job برای هر اثر جانبی | مرحلهها قابل جابهجایی و تست | جریان بین فایلها پخش است |
| تأیید خرید بر اساس مبلغ | Chain of Responsibility | حلقهها به ترتیب سقف؛ خطای صریح «تأییدکنندهای نیست» | سطح تازه = حلقهٔ تازه | قواعد در ترتیب پنهاناند |
| undo/redo در ویرایشگر | Command (+ Memento برای ویرایش پیچیده) | دو پشته؛ snapshot پیش از فرمانهای پرخطر | حافظهٔ کم، undo دقیق | اثرهای جانبی برگشتناپذیر جبران لازم دارند |
| audit log عملیات کاربر | Command | هر فرمان با کاربر و payload پایدار میشود | replay و بررسی جنایی | schema فرمانهای قدیمی باید خوانا بماند |
| ماژولهایی که به هم واکنش دارند | Observer (درونپردازه) یا Mediator | event برای واکنش مستقل؛ هماهنگکننده برای واکنش ترتیبی | coupling کم | جریان نامرئی؛ ترتیب |
switch ($method) برای قیمت/ارسال | Strategy | interface + registry/tag در container | روش تازه بدون ویرایش checkout | منطق انتخاب همچنان لازم است |
| export میلیونها سطر | Iterator | LazyCollection، lazy()، iter.Seq | حافظهٔ ثابت | cursor/اتصال طولانیمدت باز |
| گزارشهای زیاد روی یک درخت دامنه | Visitor | یک visitor برای هر گزارش | گزارش آزادانه اضافه میشود | نوع گرهٔ تازه همهٔ visitorها را ویرایش میکند |
| قواعد قابل ویرایش توسط کسبوکار | Interpreter | قاعده به شکل JSON → درخت عبارت | بدون deploy برای هر قاعده | اعتبارسنجی، نسخهگذاری و تست قواعد |
workflow سفارش
از یک enum (در Laravel) یا یک map گذار (در Go) بهعنوان منبع واحد حرکتهای مجاز استفاده کنید، از UPDATE شرطی بهعنوان اعمالکننده در دیتابیس، و از یک event برای هر گذار برای اثرهای جانبی. اثرهای جانبی را بیرون از objectهای وضعیت نگه دارید: وضعیت تصمیم میگیرد آیا، listenerها تصمیم میگیرند چه چیز دیگری رخ دهد. آزمایشگاه نسخهٔ کامل است.
زنجیرهٔ تأیید
حلقهها را از کمترین تا بیشترین اختیار مرتب کنید، به هر کدام سقف بدهید، و «از انتها افتاد» را خطای صریح کنید. اگر واحد مالی سقفها را زیاد عوض میکند، زنجیره را در پیکربندی نگه دارید. اینکه کدام حلقه تأیید کرد را log کنید (command log).
ویرایشگر undo/redo
برای هر عمل کاربر یک فرمان؛ History.Execute پشتهٔ redo را پاک میکند؛ پشته را محدود کنید؛ برای عملهایی که معکوسشان سخت حساب میشود، پیش از اجرا یک memento بگیرید و هنگام undo بازگردانید.
audit log با تاریخچهٔ فرمانها
هر درخواست تغییردهندهٔ state یک object فرمان میشود؛ invoker (user, command, payload, time) را در همان تراکنش تغییر پایدار میکند (جدول command_log بالا). این برای دیباگ امکان replay هم میدهد. اگر کل تاریخچه باید منبع حقیقت باشد، آن Event Sourcing است، نه audit log.
ماژولهای event-driven درون یک monolith
ماژولها رویداد دامنه منتشر میکنند (OrderPaid)؛ ماژولهای دیگر مشترک میشوند. قواعد: eventها واقعیتهایی در زمان گذشتهاند؛ پس از commit منتشر کنید (ShouldDispatchAfterCommit)؛ listenerهایی که I/O دارند صفشده باشند؛ هیچ listenerی فرض نکند listener دیگری اول اجرا شده. وقتی دیدید دارید مینویسید «listener ب باید بعد از listener الف اجرا شود»، آن جفت را با یک Mediator جایگزین کنید.
انتخاب
| وضعیت | پیشنهاد | تکنیک اضافه | دلیل |
|---|---|---|---|
| چند الگوریتم قابلتعویض که فراخواننده/config انتخاب میکند | Strategy | مقدار func در Go؛ tag در container لاراول | تعویض در زمان اجرا، تست جداگانه |
| دنبالهٔ ثابت، چند مرحله در هر زیرکلاس فرق دارد | Template Method (در Go: تابع + interface) | اسکلت final، hook با پیشفرض | ترتیب نمیشکند |
| رفتار به وضعیت چرخهٔ عمر بستگی دارد | State | جدول transition + UPDATE شرطی | گذار غیرمجاز ناممکن |
| درخواست باید از بررسیهایی بگذرد که ممکن است متوقفش کنند | Chain of Responsibility | middleware، Pipeline | handlerهای تکمنظوره و قابل جابهجایی |
| درخواست باید صف، retry، log یا undo شود | Command | job، idempotency key، command log | درخواست به شکل داده |
| واکنشهای مستقل زیاد به یک واقعیت | Observer | listener صفشده، dispatch پس از commit | واکنش تازه بدون ویرایش subject |
| objectهای زیاد با تعامل درهم | Mediator | یک هماهنگکننده برای هر use case | n پیوند بهجای n(n−1)/2 |
| پیمایش بدون افشای نحوهٔ ذخیره | Iterator | iter.Seq، LazyCollection | حافظهٔ ثابت، توقف زودهنگام |
| بازگرداندن حالت قبلی | Memento | جدول نسخهها، پشتهٔ محدود | کپسولهسازی حفظ میشود |
| عملیات تازه روی مجموعهٔ پایدار نوعها | Visitor | ast.Inspect؛ type switch اگر کوچک است | عملیات زیاد میشود، نوعها نه |
| شرطهای قابل ویرایش توسط کسبوکار | Interpreter | قاعدهٔ JSON + اعتبارسنجی | تغییر بدون deploy |
| دو شاخه که هرگز عوض نمیشوند | بدون الگو | if/switch | واسطه بیشتر از صرفهاش هزینه دارد |
Strategy و State و Template Method
هر سه رفتار را تغییر میدهند. refactoring.guru تفاوت اول را دقیق میگوید: «Template Method is based on inheritance» و «Strategy is based on composition» و «Template Method works at the class level, so it’s static. Strategy works on the object level, letting you switch behaviors at runtime.» و تفاوت دوم را: «In the State pattern, the particular states may be aware of each other and initiate transitions from one state to another, whereas strategies almost never know about each other.»
| سؤال | Strategy | State | Template Method |
|---|---|---|---|
| چه کسی نسخه را انتخاب میکند؟ | client/config | وضعیت فعلی (گذار) | زیرکلاس، در زمان کامپایل |
| نسخهها همدیگر را میشناسند؟ | نه | بله (وضعیت بعدی را تنظیم میکنند) | نه |
| سازوکار | ترکیب | ترکیب | وراثت |
| در طول عمر object عوض میشود؟ | بهندرت (یکبار تنظیم) | مدام | هرگز |
| مثال | محاسبهگر ارسال | چرخهٔ عمر سفارش | exporter گزارش |
Observer و pub/sub و Mediator
refactoring.guru این خانواده را توصیف میکند: «Mediator eliminates direct connections between senders and receivers, forcing them to communicate indirectly via a mediator object» در حالی که «Observer lets receivers dynamically subscribe to and unsubscribe from receiving requests.» Event Aggregator از Fowler شکل میانی است: «Channel events from multiple objects into a single object to simplify registration for clients.»
| سؤال | Observer | Pub/sub (broker) | Mediator |
|---|---|---|---|
| چه کسی چه کسی را میشناسد | subject به observerها ارجاع دارد | هیچکس؛ هر دو topic را میشناسند | همکاران میانجی را؛ میانجی همه را |
| قواعد کجاست | در هر observer | در هر subscriber | در میانجی |
| مرز پردازه | همان پردازه | بین پردازهها | معمولاً همان پردازه (orchestrator در saga بین آنها) |
| تحویل | فراخوانی همزمان | ناهمزمان، پایدار، at-least-once | همزمان یا ناهمزمان |
| Laravel | event + listener، model observer | listener صفشده، پکیجهای broker | Action هماهنگکننده |
| Go | callback، channel | کلاینتهای NATS، Kafka، RabbitMQ | struct یا goroutine مالک |
Command و Job و Transaction Script
Fowler اسکریپت تراکنش (Transaction Script) را چنین تعریف میکند: «Organizes business logic by procedures where each procedure handles a single request from the presentation.» موضوعش سازماندهی منطق است؛ Command دربارهٔ نمایش درخواست است. یک Job در Laravel یک Command است که فراخوانندهاش queue worker است. این دو با هم ترکیب میشوند: handle() یک Job اغلب یک transaction script است.
| Command (الگو) | Job در Laravel | Transaction Script | |
|---|---|---|---|
| درخواست یک object است؟ | بله | بله (در صف serialize میشود) | نه، فراخوانی procedure است |
| قابل صف/retry/undo | بله، از طراحی | صف، retry ($tries، backoff) | نه |
| اندازهٔ معمول | یک عمل | یک واحد کار پسزمینه | یک use case |
| مثال | Insert{"hi"}، RenameDocument | CapturePayment::dispatch($order) | PlaceOrderService::handle() |
در معماری: از یک پردازه تا سیستم توزیعشده
بیشتر الگوهای رفتاری طراحیهای درونپردازهایاند. وقتی سیستم شکسته میشود، هر کدام یا محلی میماند یا به یک الگوی پیامرسانی با نام دیگر و معنای شکست قویتر تبدیل میشود.
Monolith (یکپارچه): یک پردازه، یک دیتابیس
چطور ظاهر میشود: کلاس و تابع. زنجیرهٔ middleware، event و listener، job، state machine با enum، strategyهای bindشده در container.
سادهترین استفادهٔ درست: State روی model با UPDATE شرطی؛ Observer با ShouldDispatchAfterCommit؛ Command به شکل job صفشده روی driver صف database یا Redis؛ Strategy با binding در container.
مثال (ساده): یک وبلاگ: enum PostStatus (draft، scheduled، published)، job PublishScheduledPosts که scheduler اجرا میکند، event PostPublished با listener صفشدهٔ NotifySubscribers.
مثال (پیچیده): یک فروشگاه: Pipeline در checkout (validate، رزرو موجودی، strategy تخفیف، ثبت سفارش) درون یک تراکنش؛ enum OrderStatus؛ event OrderStatusChanged با listenerهایی برای ایمیل، export انبار و analytics؛ ویرایشهای undoپذیر ادمین در command_log.
Modular monolith و چند دیتابیس
چطور ظاهر میشود: ماژولها از طریق event (Observer) یا از طریق یک هماهنگکننده (Mediator) ارتباط دارند، هرگز با صدا زدن جزئیات داخلی هم یا نوشتن در جدولهای هم.
قواعد: eventها API منتشرشدهٔ یک ماژولاند، پس مثل API نسخهگذاریشان کنید؛ هر ماژول در service provider خودش مشترک میشود؛ یک جریان بینماژولی که باید به ترتیب رخ دهد (رزرو، فاکتور، اعلان) در یک use case هماهنگکننده زندگی میکند، نه در زنجیرهای از listenerها که همدیگر را صدا میزنند. اگر ماژولها دیتابیس جدا دارند، listener در ماژول ب نمیتواند به تراکنش ماژول الف بپیوندد: با آن مثل مصرفکنندهٔ راه دور رفتار کنید و idempotentاش کنید.
مثال: Billing رویداد InvoicePaid را منتشر میکند؛ Fulfilment گوش میدهد و shipment میسازد؛ CheckoutMediator در ماژول Checkout تنها کدی است که ترتیب Inventory → Billing → Notifications را میداند.
میکروسرویسها: الگوها با شبکه در میانه
چه میماند و چه عوض میشود:
| الگوی درونپردازه | شکل توزیعشده | چه باید اضافه کنید | بعدی بخوانید |
|---|---|---|---|
| Observer | publish/subscribe با broker | outbox، at-least-once، مصرفکنندهٔ idempotent، تکامل schema | Event-Driven Architecture، Outbox |
| Command | پیام روی صف کار | idempotency key، retry با backoff، DLQ | Competing Consumers، Retry & Backoff، DLQ |
| State | saga / workflow پایدار | state پایدار، timeout، جبران | Saga، Durable Workflows |
| Mediator | orchestrator در saga / process manager | correlation id، ذخیرهٔ state | Advanced Routing |
| Chain of Responsibility | filterهای gateway، سیاستهای service mesh، routing slip | timeout برای هر گام، tracing | Advanced Routing |
| Memento | snapshot در ذخیرهگاه event-sourced | snapshot + replay | Event Sourcing & CQRS |
Checkout service Broker Payment service Shipping service
1 INSERT order(pending) + outbox row in one transaction
2 relay publishes OrderPlaced -> orders topic
3 -> consume, charge, idempotency key=order id
4 <- PaymentCaptured
5 consume -> order: pending -> paid (conditional UPDATE)
6 publish OrderPaid -> -> create shipment
a lost or duplicated message must never move the state machine twiceمثال: state machine سفارش در سرویس checkout زندگی میکند؛ سرویسهای دیگر هرگز وضعیتش را تنظیم نمیکنند، eventهایی میفرستند که مالک به گذار تبدیل میکند. این برای هر state machine یک نویسنده نگه میدارد.
دادههای توزیعشده: replica، cache و نمونههای متعدد
جایی که الگوهای درونپردازه میشکنند:
- Observer با چند نمونهٔ برنامه: subject درون حافظه روی نمونهٔ A به observerهای نمونهٔ B خبر نمیدهد. از صف یا broker استفاده کنید (pub/sub در Redis شلیکوفراموش است: subscriberی که خاموش است پیام را از دست میدهد؛ Redis Streams یا یک broker واقعی نگهشان میدارد).
- State خواندهشده از replica: replicaی عقبمانده ممکن است
pendingنشان دهد در حالی که primary بهpaidرفته؛ گذارها باید از primary بخوانند و بنویسند (UPDATEشرطی همین کار را میکند). - State در cache: وضعیت سفارش در Redis که یک Eloquent observer invalidateاش میکند بین نوشتن و
Cache::forgetکهنه است؛ برای state machine فقط برای نمایش cache کنید. - Memento بین سرویسها: snapshot دادهٔ یک سرویس دادهٔ سرویسهای دیگر را ندارد؛ بازگرداندنش میتواند قیدهای بینسرویسی را بشکند.
- ناهمخوانی config برای Strategy: نمونهها باید دربارهٔ strategy فعال توافق داشته باشند؛ انتخاب را از config مشترک یا سرویس feature flag بخوانید، نه از فایل محلی.
مسیر مقیاسپذیری: 1×، 10×، 100×
| مقیاس | ساختار | کاربرد الگوها |
|---|---|---|
| 1× (یک برنامه، یک تیم) | Monolith | state با enum، listener همزمان، job روی صف database/Redis، checkout با Pipeline |
| 10× (چند تیم، ترافیک بیشتر) | Modular monolith، queue workerهای جداگانه مقیاسپذیر | listener صفشده، event پس از commit، هماهنگکننده برای هر use case، command log، worker pool به سبک Horizon |
| 100× (سرویسهای زیاد) | سرویس برای هر قابلیت، broker | outbox + pub/sub، saga برای state machine، مصرفکنندهٔ idempotent، schema registry برای قرارداد eventها |
آزمایشگاه: state machine سفارش، checkout با pipeline و observerها
یک checkout را دوبار میسازید، در Go و در Laravel: state machine سفارش (State)، pipeline checkout که مرحلههایش میتوانند زنجیره را متوقف و جبران کنند (Chain of Responsibility، با یک Strategy تخفیف بهعنوان یکی از مرحلهها)، و listenerهایی که پس از commit به تغییر وضعیت واکنش نشان میدهند (Observer).
راهاندازی Go.
cd docs/snippets/design/behavioral-patterns/go
gofmt -l . && go vet ./... # no output, no errors
go test -race ./lab/ -v # 4 tests: transitions, happy path, payment failure, empty cartstate machine به شکل داده، eventهایی که روی سفارش ثبت و پس از «commit» برداشته میشوند:
// Package lab combines three behavioral patterns into one checkout:
// a State machine for the order, a Chain of Responsibility pipeline for
// checkout steps, and Observers for side effects.
package lab
import (
"errors"
"fmt"
)
type Status string
const (
Pending Status = "pending"
Paid Status = "paid"
Shipped Status = "shipped"
Delivered Status = "delivered"
Cancelled Status = "cancelled"
Refunded Status = "refunded"
)
// transitions is the whole state machine as data: from -> allowed targets.
// The same table becomes a SQL CHECK or a lookup table in the database.
var transitions = map[Status][]Status{
Pending: {Paid, Cancelled},
Paid: {Shipped, Refunded},
Shipped: {Delivered},
}
var ErrTransition = errors.New("illegal transition")
func (s Status) CanTransitionTo(next Status) bool {
for _, t := range transitions[s] {
if t == next {
return true
}
}
return false
}
// StatusChanged is the event observers receive.
type StatusChanged struct {
OrderID string
From, To Status
}
type Order struct {
ID string
Total int64
Status Status
events []StatusChanged
}
// TransitionTo changes state and records an event; it never notifies directly,
// so the caller can publish only after the transaction commits.
func (o *Order) TransitionTo(next Status) error {
if !o.Status.CanTransitionTo(next) {
return fmt.Errorf("%w: %s -> %s", ErrTransition, o.Status, next)
}
o.events = append(o.events, StatusChanged{o.ID, o.Status, next})
o.Status = next
return nil
}
// PullEvents hands recorded events to the caller and clears them.
func (o *Order) PullEvents() []StatusChanged {
ev := o.events
o.events = nil
return ev
}زنجیرهٔ checkout؛ Reserve وقتی مرحلهٔ بعدی شکست بخورد کار خودش را برمیگرداند:
package lab
import (
"context"
"errors"
"sync"
)
// Cart is the input that flows through the checkout pipeline.
type Cart struct {
CustomerID string
Lines map[string]int // sku -> qty
Subtotal int64
Discount int64
Order *Order
}
// Next calls the rest of the pipeline.
type Next func(ctx context.Context, c *Cart) error
// Step is one handler of the chain: it may work before and after next,
// or stop the chain by returning without calling next.
type Step func(ctx context.Context, c *Cart, next Next) error
// Pipeline runs steps in order; the terminal handler places the order.
func Pipeline(steps ...Step) Next {
final := Next(func(context.Context, *Cart) error { return nil })
for i := len(steps) - 1; i >= 0; i-- {
step, next := steps[i], final
final = func(ctx context.Context, c *Cart) error { return step(ctx, c, next) }
}
return final
}
var (
ErrEmptyCart = errors.New("cart is empty")
ErrOutOfStock = errors.New("out of stock")
)
func ValidateCart(ctx context.Context, c *Cart, next Next) error {
if len(c.Lines) == 0 {
return ErrEmptyCart // stops the chain
}
return next(ctx, c)
}
// Stock is a tiny in-memory inventory; Reserve is the step's side effect.
type Stock struct {
mu sync.Mutex
Qty map[string]int
}
func (s *Stock) Reserve(ctx context.Context, c *Cart, next Next) error {
s.mu.Lock()
for sku, n := range c.Lines {
if s.Qty[sku] < n {
s.mu.Unlock()
return ErrOutOfStock
}
}
for sku, n := range c.Lines {
s.Qty[sku] -= n
}
s.mu.Unlock()
if err := next(ctx, c); err != nil {
s.mu.Lock() // compensate: the step undoes its own work on failure
for sku, n := range c.Lines {
s.Qty[sku] += n
}
s.mu.Unlock()
return err
}
return nil
}
// ApplyDiscount is a strategy plugged into a step.
func ApplyDiscount(rule func(subtotal int64) int64) Step {
return func(ctx context.Context, c *Cart, next Next) error {
c.Discount = rule(c.Subtotal)
return next(ctx, c)
}
}
// Charge is the payment port; tests pass a fake.
type Charge func(ctx context.Context, customerID string, cents int64) error
func PlaceOrder(charge Charge, newID func() string) Step {
return func(ctx context.Context, c *Cart, next Next) error {
o := &Order{ID: newID(), Total: c.Subtotal - c.Discount, Status: Pending}
if err := charge(ctx, c.CustomerID, o.Total); err != nil {
return err // Reserve, earlier in the chain, compensates
}
if err := o.TransitionTo(Paid); err != nil {
return err
}
c.Order = o
return next(ctx, c)
}
}package lab
import "sync"
// Bus is an in-process observer registry keyed by target status.
type Bus struct {
mu sync.RWMutex
listeners map[Status][]func(StatusChanged)
}
func (b *Bus) On(to Status, fn func(StatusChanged)) {
b.mu.Lock()
defer b.mu.Unlock()
if b.listeners == nil {
b.listeners = map[Status][]func(StatusChanged){}
}
b.listeners[to] = append(b.listeners[to], fn)
}
// Publish calls listeners in registration order. Call it after commit.
func (b *Bus) Publish(events ...StatusChanged) {
for _, e := range events {
b.mu.RLock()
fns := b.listeners[e.To]
b.mu.RUnlock()
for _, fn := range fns {
fn(e)
}
}
}package lab
import (
"context"
"errors"
"testing"
)
func TestTransitions(t *testing.T) {
cases := []struct {
from, to Status
ok bool
}{
{Pending, Paid, true},
{Pending, Shipped, false},
{Paid, Shipped, true},
{Shipped, Cancelled, false},
{Cancelled, Paid, false},
}
for _, c := range cases {
o := &Order{ID: "o1", Status: c.from}
err := o.TransitionTo(c.to)
if (err == nil) != c.ok {
t.Errorf("%s -> %s: err=%v, want ok=%v", c.from, c.to, err, c.ok)
}
if err != nil && !errors.Is(err, ErrTransition) {
t.Errorf("want ErrTransition, got %v", err)
}
}
}
func checkout(stock *Stock, charge Charge) Next {
return Pipeline(
ValidateCart,
stock.Reserve,
ApplyDiscount(func(s int64) int64 { return s / 10 }),
PlaceOrder(charge, func() string { return "o-1" }),
)
}
func TestCheckoutHappyPathPublishesPaid(t *testing.T) {
stock := &Stock{Qty: map[string]int{"mug": 3}}
var charged int64
charge := func(_ context.Context, _ string, cents int64) error { charged = cents; return nil }
cart := &Cart{CustomerID: "c1", Lines: map[string]int{"mug": 2}, Subtotal: 2_000}
if err := checkout(stock, charge)(context.Background(), cart); err != nil {
t.Fatal(err)
}
if charged != 1_800 || cart.Order.Status != Paid || stock.Qty["mug"] != 1 {
t.Fatalf("charged=%d status=%s stock=%d", charged, cart.Order.Status, stock.Qty["mug"])
}
var got []string
bus := &Bus{}
bus.On(Paid, func(e StatusChanged) { got = append(got, "email:"+e.OrderID) })
bus.On(Paid, func(e StatusChanged) { got = append(got, "warehouse:"+e.OrderID) })
bus.Publish(cart.Order.PullEvents()...)
if len(got) != 2 || got[0] != "email:o-1" || got[1] != "warehouse:o-1" {
t.Fatalf("observers got %v", got)
}
}
func TestPaymentFailureReleasesStock(t *testing.T) {
stock := &Stock{Qty: map[string]int{"mug": 3}}
declined := errors.New("card declined")
charge := func(context.Context, string, int64) error { return declined }
cart := &Cart{CustomerID: "c1", Lines: map[string]int{"mug": 2}, Subtotal: 2_000}
err := checkout(stock, charge)(context.Background(), cart)
if !errors.Is(err, declined) {
t.Fatalf("want declined, got %v", err)
}
if stock.Qty["mug"] != 3 {
t.Fatalf("stock not released: %d", stock.Qty["mug"])
}
}
func TestEmptyCartStopsChain(t *testing.T) {
called := false
charge := func(context.Context, string, int64) error { called = true; return nil }
err := checkout(&Stock{Qty: map[string]int{}}, charge)(context.Background(), &Cart{})
if !errors.Is(err, ErrEmptyCart) || called {
t.Fatalf("err=%v charged=%v", err, called)
}
}راهاندازی Laravel. در یک برنامهٔ Laravel 13 با جدول products (price، stock)، جدول orders (customer_id، total، status)، enum OrderStatus و model Order از snippet State و event و listenerها از snippet Observer:
<?php
// Lab: pipeline-based checkout (Chain of Responsibility) that creates an order
// whose status is an enum state machine (State) and whose changes are observed
// by listeners (Observer). Uses App\Enums\OrderStatus and App\Models\Order from State.php.
namespace App\Checkout;
use App\Enums\OrderStatus;
use App\Models\Order;
use App\Models\Product;
use App\Services\Payments;
use Closure;
use DomainException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Pipeline;
final class CheckoutData
{
public int $subtotal = 0;
public int $discount = 0;
public ?Order $order = null;
/** @param array<int, int> $lines product id => quantity */
public function __construct(public readonly int $customerId, public readonly array $lines) {}
}
final class ValidateCart
{
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
if ($data->lines === []) {
throw new DomainException('Cart is empty'); // stops the chain
}
return $next($data);
}
}
final class ReserveStock
{
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
foreach ($data->lines as $productId => $qty) {
// Atomic conditional decrement: no read-modify-write race.
$ok = Product::whereKey($productId)->where('stock', '>=', $qty)->decrement('stock', $qty);
if ($ok === 0) {
throw new DomainException("Product {$productId} is out of stock");
}
$data->subtotal += Product::whereKey($productId)->value('price') * $qty;
}
return $next($data); // a later failure rolls this back with the transaction
}
}
final class ApplyDiscount
{
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
$data->discount = $data->subtotal >= 10_000 ? intdiv($data->subtotal, 10) : 0;
return $next($data);
}
}
final class PlaceOrder
{
public function __construct(private readonly Payments $payments) {} // resolved by the container
public function __invoke(CheckoutData $data, Closure $next): CheckoutData
{
$order = Order::create([
'customer_id' => $data->customerId,
'total' => $data->subtotal - $data->discount,
'status' => OrderStatus::Pending,
]);
$this->payments->charge($data->customerId, $order->total, idempotencyKey: "order-{$order->id}");
$order->transitionTo(OrderStatus::Paid); // fires OrderStatusChanged after commit
$data->order = $order;
return $next($data);
}
}
final class Checkout
{
public function __invoke(int $customerId, array $lines): Order
{
return DB::transaction(fn () => Pipeline::send(new CheckoutData($customerId, $lines))
->through([ValidateCart::class, ReserveStock::class, ApplyDiscount::class, PlaceOrder::class])
->thenReturn()
->order);
}
}<?php
namespace Tests\Feature;
use App\Checkout\Checkout;
use App\Enums\OrderStatus;
use App\Events\OrderStatusChanged;
use App\Models\Order;
use App\Models\Product;
use App\Services\Payments;
use DomainException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use RuntimeException;
use Tests\TestCase;
final class CheckoutTest extends TestCase
{
use RefreshDatabase;
public function test_state_machine_rejects_illegal_transitions(): void
{
$this->assertTrue(OrderStatus::Pending->canTransitionTo(OrderStatus::Paid));
$this->assertFalse(OrderStatus::Pending->canTransitionTo(OrderStatus::Shipped));
$this->assertFalse(OrderStatus::Cancelled->canTransitionTo(OrderStatus::Paid));
}
public function test_checkout_charges_once_and_announces_paid(): void
{
Event::fake([OrderStatusChanged::class]);
$this->mock(Payments::class)->shouldReceive('charge')->once();
$mug = Product::factory()->create(['price' => 6_000, 'stock' => 3]);
$order = (new Checkout)(customerId: 1, lines: [$mug->id => 2]);
$this->assertSame(OrderStatus::Paid, $order->status);
$this->assertSame(10_800, $order->total); // 12000 - 10% discount
$this->assertSame(1, $mug->fresh()->stock);
Event::assertDispatched(OrderStatusChanged::class,
fn (OrderStatusChanged $e) => $e->from === OrderStatus::Pending && $e->to === OrderStatus::Paid);
}
public function test_payment_failure_rolls_back_stock_and_order(): void
{
Event::fake([OrderStatusChanged::class]);
$this->mock(Payments::class)->shouldReceive('charge')->andThrow(new RuntimeException('declined'));
$mug = Product::factory()->create(['price' => 1_000, 'stock' => 3]);
$this->expectException(RuntimeException::class);
try {
(new Checkout)(customerId: 1, lines: [$mug->id => 2]);
} finally {
$this->assertSame(3, $mug->fresh()->stock);
$this->assertSame(0, Order::count());
Event::assertNotDispatched(OrderStatusChanged::class);
}
}
public function test_empty_cart_stops_the_chain(): void
{
$this->mock(Payments::class)->shouldNotReceive('charge');
$this->expectException(DomainException::class);
(new Checkout)(customerId: 1, lines: []);
}
}نسخهٔ Laravel کارت را درون DB::transaction charge میکند. اگر commit پس از charge موفق شکست بخورد، پول گرفته شده و سفارش از بین رفته است؛ برای همین charge یک idempotency key (order-{id}) دارد و یک job تطبیق (Reconciliation) باید chargeهای یتیم را refund کند. بین سرویسها این یک گام saga با جبران (Compensation) میشود.
آزمایشها.
go test -race ./lab/ -run TestTransitions -vرا اجرا کنید. انتظار:--- PASS. سطر{Paid, Pending, false}را به جدول اضافه کنید؛ همچنان پاس میشود. حالاPaid: {Shipped, Refunded, Pending}را درtransitionsبگذارید؛ سطر تازه شکست میخورد. ماشین همان جدول است.- در
TestCheckoutHappyPathPublishesPaidدو فراخوانیbus.Onرا جابهجا کنید. انتظار: assertion ترتیب شکست میخورد، که نشان میدهد observerها به ترتیب ثبت اجرا میشوند. اگر طراحیتان به ترتیب ثابت نیاز دارد، بهجایش از Mediator استفاده کنید. ValidateCartرا بعد ازstock.Reserveدرcheckout()بگذارید.TestEmptyCartStopsChainرا اجرا کنید: همچنان پاس میشود (سبد خالی چیزی رزرو نمیکند)، اما روی سبد واقعی حالا پیش از validate رزرو میکنید. باگ ترتیب در زنجیره بیصداست؛ ترتیب middleware را مثل کد review کنید.- بلوک جبران را در
Stock.Reserveپاک کنید. انتظار:TestPaymentFailureReleasesStockباstock not released: 1شکست میخورد. در Laravel همین تضمین ازDB::transactionدور pipeline میآید؛ بین سرویسها به جبران saga نیاز دارد. - Laravel:
php artisan test --filter=CheckoutTestرا اجرا کنید. سپسShouldDispatchAfterCommitرا ازOrderStatusChangedبردارید و بعد ازPlaceOrderیک مرحلهٔ شکستخورده اضافه کنید؛ با listenerهای واقعی (بدون fake)، ایمیل پرداخت برای سفارشی فرستاده میشود که rollback شده است. - دو ترمینال روی PostgreSQL:
UPDATE ... WHERE status = 'pending'شرطی را برایpaidدر یک session درونBEGINاجرا کنید و همان را برایcancelledدر session دیگر. انتظار: دومی منتظر میماند و پس از commit اولیUPDATE 0گزارش میدهد.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| الگو باید شبیه نمودار کلاس GoF باشد | در Go بیشتر الگوهای رفتاری یک نوع تابع یا interface کوچکاند |
| Observer ناهمزمان است | Observer کلاسیک و listenerهای پیشفرض Laravel همزماناند؛ صفکردن یک انتخاب است (ShouldQueue) |
| Observer و pub/sub یکیاند | pub/sub یک broker اضافه میکند، با جدایی در زمان و پردازه، پایداری و معنای تحویل |
| event bus همان Mediator است | bus مسیریابی میکند؛ Mediator مالک قواعد هماهنگی است |
ستون status همان الگوی State است | الگو جایی است که قواعد گذار زندگی میکنند؛ ستون فقط ذخیره است |
| Strategy و State دو اسم برای یک چیزند | strategy را client انتخاب میکند و همدیگر را نمیشناسند؛ state وضعیت بعدی را انتخاب میکند |
| در Chain of Responsibility فقط یک handler کار میکند | در زنجیرهٔ middleware همه کار میکنند؛ شکل GoF در اولین قادر متوقف میشود |
| Command یعنی دستور CLI | Command هر درخواستی به شکل object است: job، عمل ویرایشگر، پیام صفشده |
| undo همیشه Command است | undo با Memento snapshot نگه میدارد؛ خیلی از ویرایشگرها هر دو را ترکیب میکنند |
| Visitor مدل را توسعهپذیر میکند | عملیات را توسعهپذیر و افزودن نوع را سختتر میکند (expression problem) |
| Iterator در Go بیربط است | از Go 1.23، iter.Seq iterator استاندارد است و stdlib آن را برمیگرداند |
| Template Method هرجا کلاس پایه هست خوب است | این الگوی مبتنی بر وراثت است؛ وقتی نسخهها زیاد میشوند ترکیب را ترجیح دهید |
| الگوی بیشتر = طراحی بهتر | هر الگو واسطه اضافه میکند؛ وقتی تغییرپذیری واقعی است به کارش ببرید |
| Interpreter برای ساختن زبان برنامهنویسی است | برای گرامرهای کوچک و پایدار است؛ گرامر بزرگ parser یا موتور موجود میخواهد |
چکیده (Cheat sheet)
| موضوع | به خاطر بسپارید |
|---|---|
| خانواده | رفتاری = الگوریتم + تخصیص مسئولیت + ارتباط |
| Template Method | اسکلت ثابت، مرحلهٔ متغیر؛ وراثت؛ در Go: تابع + interface |
| Chain | handlerها به ترتیب، هر کدام میتواند متوقف کند؛ middleware، Pipeline؛ ترتیب مهم است |
| State | رفتار برای هر وضعیت؛ جدول transition + UPDATE شرطی؛ saga بین سرویسها |
| Command | درخواست به شکل object؛ صف، retry، undo، audit؛ Job در Laravel، Bus::chain |
| Observer | یکبهچند، درونپردازه، پیشفرض همزمان؛ ShouldQueue، ShouldDispatchAfterCommit |
| Strategy | الگوریتم قابلتعویض؛ func در Go، slices.SortFunc؛ tag، Gate، Policy در Laravel |
| Iterator | پیمایش بدون افشای ذخیره؛ iter.Seq، iter.Pull؛ generator، LazyCollection |
| Mediator | هاب مالک قواعد تعامل؛ n پیوند نه n(n−1)/2؛ مراقب میانجی خدا باشید |
| Memento | snapshot مات؛ caretaker هرگز آن را نمیخواند؛ تاریخچه را محدود کنید |
| Visitor | double dispatch؛ عملیات تازه آسان، نوع تازه سخت؛ ast.Walk، ast.Inspect |
| Interpreter | کلاس برای هر قاعدهٔ گرامر؛ DSL کوچک؛ درخت Composite |
| Strategy و State | چه کسی انتخاب میکند: فراخواننده یا وضعیت فعلی |
| Observer و pub/sub | همان پردازه و همزمان، در برابر broker، ناهمزمان، پایدار |
| شکلهای توزیعشده | Observer → pub/sub + outbox؛ Command → صف job؛ State/Mediator → saga |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — Order شما if ($order->status === 'paid') را در ۱۴ جا دارد. کدام الگو، و دیتابیس هم باید چه کند؟ حیاتی
پاسخ
پاسخ: State: گذارهای مجاز را به یک enum (یا نوعهای وضعیت) با canTransitionTo منتقل کنید و در دیتابیس با UPDATE ... WHERE status = :from شرطی اعمالشان کنید تا دو worker نتوانند هر دو گذار را انجام دهند. State و جدول transition را ببینید.
۲ — تفاوت یکخطی Strategy و State چیست؟ حیاتی
پاسخ
پاسخ: strategy را client انتخاب میکند و strategyها همدیگر را نمیشناسند؛ state خودش وضعیت بعدی را تعیین میکند. Strategy و State و Template Method را ببینید.
۳ — یک listener در Laravel هنگام پرداخت سفارش ایمیل میفرستد، اما مشتریها برای سفارشهای rollbackشده ایمیل گرفتند. چرا، و راهحل چیست؟ حیاتی
پاسخ
پاسخ: event درون تراکنشی dispatch شد که بعداً rollback شد و listener بلافاصله اجرا (یا صف) شد. ShouldDispatchAfterCommit را روی event پیاده کنید، یا eventهای ثبتشده را پس از commit منتشر کنید. بین سرویسها از outbox استفاده کنید. اعلان همزمان و صفشده را ببینید.
۴ — چرا Job صفشده در Laravel نمونهای از الگوی Command است؟ مهم
پاسخ
پاسخ: درخواست (پارامترهای constructor) یک object است که serialize، صف، retry و بعداً توسط یک invoker (worker) اجرا میشود و invoker گیرندهای را که در handle() inject شده صدا میزند. Command را ببینید.
۵ — در زنجیرهٔ middleware در Go که با Chain(h, Logging, RequireToken) ساخته شده، کدام اول اجرا میشود، و آیا Logging پاسخ 401 را میبیند؟ مهم
پاسخ
پاسخ: Logging اول اجرا میشود (بیرونیترین) و چون بقیه را پیچیده، میتواند پاسخ را در مسیر خروج ببیند، از جمله 401 که RequireToken نوشته. پیاز را ببینید.
۶ — نوع سطر تازهٔ GiftWrapLine به فاکتور اضافه میکنید. در طراحی Visitor چه میشود؟ تکمیلی
پاسخ
پاسخ: هر interface و پیادهسازی visitor به متد تازهٔ visitGiftWrap نیاز دارد. Visitor عملیات تازه را ارزان و نوع تازه را گران میکند. Visitor را ببینید.
۷ — هر iterator نوع push در Go وقتی yield مقدار false برمیگرداند چه باید بکند، و فراخوانندگان iter.Pull همیشه باید چه کنند؟ مهم
پاسخ
پاسخ: بلافاصله متوقف شود و برگردد (ادامهٔ صدا زدن yield panic میدهد). فراخوانندگان iter.Pull باید تابع stop برگشتی را صدا بزنند، معمولاً با defer. iterator نوع push و pull را ببینید.
۸ — listenerهای checkout شما «listener ب باید بعد از listener الف اجرا شود» هستند. چه اشکالی دارد و بهجایش از چه استفاده کنیم؟ مهم
پاسخ
پاسخ: observerها باید مستقل باشند؛ وابستگی ترتیبی منطق هماهنگی است. جریان ترتیبی را در یک Mediator (use case هماهنگکننده) بگذارید و eventها را برای واکنشهای مستقل نگه دارید. ماژولهای event-driven را ببینید.
۹ — undo با Command یا با Memento برای «اعمال فیلتر روی یک تصویر 4K»؟ تکمیلی
پاسخ
پاسخ: معمولاً Memento (snapshot پیش از تغییر) چون معکوس یک فیلتر قابل محاسبه نیست؛ تاریخچه را محدود کنید چون snapshotها بزرگاند. برای «تغییر نام لایه» undo با Command ارزانتر است. پشتههای undo را ببینید.
۱۰ — وقتی subject و observerها سرویسهای جدا باشند Observer به چه تبدیل میشود، و چه سه چیزی باید اضافه کنید؟ مهم
پاسخ
پاسخ: publish/subscribe از طریق broker؛ یک transactional outbox (انتشار مطمئن پس از commit)، مصرفکنندهٔ idempotent (تحویل at-least-once) و schema نسخهگذاریشده برای eventها اضافه کنید. میکروسرویسها را ببینید.
۱۱ — ast.Inspect کجای طیف Visitor است؟ تکمیلی
پاسخ
پاسخ: Visitor بدون boilerplate ارسال دوگانه است: پیمایش ثابت است (عمقاول)، عملیات یک closure است و روی گره type switch میکنید. ast.Walk شکل interface با Visit(node) Visitor است. Visitor را ببینید.
واژهنامه
| اصطلاح | معنی |
|---|---|
| الگوی رفتاری (Behavioral pattern) | خانوادهٔ GoF دربارهٔ الگوریتم، تخصیص مسئولیت و ارتباط بین objectها |
| Gang of Four (GoF) | Gamma، Helm، Johnson، Vlissides، نویسندگان Design Patterns (۱۹۹۴) |
| Template Method | اسکلت الگوریتم در کلاس پایه، مرحلهها override شده در زیرکلاس |
| قلاب (Hook) | مرحلهای با پیادهسازی پیشفرض که زیرکلاس میتواند override کند |
| اصل هالیوود (Hollywood principle) | «ما را صدا نزن، ما صدایت میزنیم»: فریمورک یا کلاس پایه کد شما را صدا میزند |
| Chain of Responsibility | درخواست در طول handlerها میرود، هر کدام رسیدگی، پاس یا متوقف میکند |
| Middleware | Chain of Responsibility برای درخواست HTTP (Laravel، net/http) |
| Pipeline | facade لاراول که هر ورودی را با $next از pipeها عبور میدهد |
| State | objectی که رفتارش با وضعیت داخلی عوض میشود؛ وضعیتها گذار را انتخاب میکنند |
| ماشین حالت متناهی (Finite state machine، FSM) | وضعیتها، رویدادها و گذارهای مجاز |
| جدول گذار (Transition table) | state machine به شکل داده: از → مقصدهای مجاز |
| Command | درخواستی تبدیلشده به object که قابل صف، log، retry و undo است |
| فراخواننده (Invoker) | فرمانها را اجرا میکند (دکمه، worker، history) |
| گیرنده (Receiver) | objectی که کار واقعی فرمان را میکند |
| Job | Command صفشدهٔ Laravel (ShouldQueue، dispatch، Bus::chain) |
| پشتهٔ Undo / redo | دو پشته از فرمانهای اجراشده و برگشته؛ فرمان تازه redo را پاک میکند |
| Observer | subject به observerهای مشترک خبر میدهد، درونپردازه |
| Subject (ناشر، publisher) | objectی که دیگران ناظرش هستند |
| Listener | ناظر یک کلاس event در Laravel |
| Eloquent observer | کلاسی با متدهای همنام رویدادهای model، ثبتشده با #[ObservedBy] |
ShouldQueue | interface لاراول که listener یا job را روی صف اجرا میکند |
ShouldDispatchAfterCommit | interface لاراول که event را تا commit تراکنش نگه میدارد |
| Lapsed listener | observerی که هرگز unsubscribe نشده و subject زنده نگهش داشته (نشت حافظه) |
| Pub/sub | انتشار/اشتراک از طریق broker؛ هیچ طرف دیگری را نمیشناسد |
| Event aggregator | Fowler: یک object که eventهای منبعهای زیاد را به یک جا هدایت میکند |
| Event bus | مسیریاب عمومی درونپردازهٔ event به subscriberها |
| Strategy | خانوادهای از الگوریتمهای قابلتعویض پشت یک interface |
| Tagged bindings | tag/tagged/#[Tag] در container لاراول برای resolve همهٔ پیادهسازیها |
| Gate / Policy | closure / کلاسهای مجوز در Laravel؛ strategy برای «آیا کاربر مجاز است» |
| Iterator | دسترسی ترتیبی به عناصر بدون افشای نمایش داخلی |
iter.Seq / iter.Seq2 | نوعهای iterator نوع push در Go 1.23 که یک یا دو مقدار yield میکنند |
iter.Pull | iterator نوع push را به توابع next/stop تبدیل میکند |
yield | callback (Go) یا کلیدواژه (generatorهای PHP) که عنصر بعدی را تحویل میدهد |
LazyCollection | collection لاراول با پشتوانهٔ generator؛ حافظهٔ کم |
| Mediator | objectی که نحوهٔ تعامل مجموعهای از objectها را در خود دارد |
| همکار (Colleague) | objectی که فقط با میانجی حرف میزند |
| Memento | snapshot مات از state یک object |
| سازنده (Originator) | objectی که memento میسازد و از آن بازمیگردد |
| نگهدارنده (Caretaker) | mementoها را بدون خواندن نگه میدارد (پشته، جدول نسخهها) |
| Visitor | عملیات روی مجموعهٔ ثابت نوعها، یک کلاس برای هر عملیات |
| ارسال دوگانه (Double dispatch) | انتخاب متد بر اساس دو نوع زمان اجرا: عنصر با accept، عملیات با visitX |
| مسئلهٔ بیان (Expression problem) | معاوضه بین افزودن نوع و افزودن عملیات |
ast.Walk / ast.Inspect | Visitor در Go و پیمایش مبتنی بر closure روی درخت نحو |
| Interpreter | کلاس برای هر قاعدهٔ گرامر؛ ارزیابی جمله به شکل درخت عبارت |
| عبارت پایانی / ناپایانی (Terminal / nonterminal expression) | قاعدهٔ برگ (مقایسه) / قاعدهٔ مرکب (and، or) |
| Transaction Script | Fowler: منطق کسبوکار به شکل یک procedure برای هر درخواست |
| Saga | state machine توزیعشده از تراکنشهای محلی با جبران |
| جبران (Compensation) | عملی که گام قبلی را از نظر معنایی برمیگرداند |
| Outbox | جدولی که در همان تراکنش تغییر نوشته و به broker رله میشود |
| Idempotency key | شناسهای که تکرار یک فرمان را امن میکند |
| Macroable | trait لاراول که در زمان اجرا متد اضافه میکند (Collection::macro)؛ سازوکار توسعه |
| Scheduler | جدول زمانی لاراول که job و command را فرامیخواند (Schedule::job) |
منابع
- E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994 (متن کتاب برای این صفحه خوانده نشد؛ اطلاعات از Wikipedia: Design Patterns)
- refactoring.guru: Behavioral patterns، Template Method، Chain of Responsibility، State، Command، Observer، Strategy، Iterator، Mediator، Memento، Visitor
- Wikipedia (منبع ثانویه): Interpreter pattern، Mediator pattern
- Martin Fowler: Transaction Script، Event Aggregator
- Go: Range Over Function Types (Go blog)، iter، sort، slices، go/ast، context، net/http
- Laravel 13: Helpers: Pipeline، Middleware، Events، Eloquent: Observers، Eloquent: Enum casting، Queues، Authorization، Collections: Lazy Collections, Macros، Service Container: Tagging، Task Scheduling
- PostgreSQL: CHECK constraints، Error codes
- MySQL 8.0: CHECK constraints، Server error reference