Applying Patterns in Real Systems: Selection, Combination & Anti-Patterns
"It's a statement that some capability we presume our software needs in the future should not be built now because “you aren't gonna need it”." — Martin Fowler، Yagni، martinfowler.com، ۲۶ مه ۲۰۱۵
خلاصه (Summary): الگو (Pattern) پاسخ به «نیرو»هاست، نه تزیین کد. این فصل نشان میدهد الگو را چطور انتخاب کنیم (یا انتخاب نکنیم)، کدام جفتها همیشه کنار هم میآیند، چطور الگو را در کد واقعی بخوانیم، نشانههای بیشطراحی (Over-engineering) کداماند، چطور با گامهای کوچک به سمت الگو refactor کنیم، و وقتی یک feature از مونولیت بیرون میرود چه الگوهایی زنده میمانند. تمرکز (Focus): روش انتخاب، هفت ترکیب پرتکرار، زبان الگو (Pattern Language) برای هر دامنه، خواندن کتابخانهٔ استاندارد Go و هستهٔ Laravel، چگالی الگو (Pattern Density)، حرکتهای Kerievsky برای refactoring به الگو، ضدالگوها در استفادهٔ الگو، الگوهای سطح سرویس، ADR، تست، و یک مطالعهٔ موردی کامل موتور قیمتگذاری در Go و Laravel. هدف یادگیری (Learning goal): با یک درخواست تغییر، نیرو را نام ببرید، دو یا سه الگوی نامزد را با پیامدهایشان فهرست کنید، سادهترین گزینهٔ کارآمد را انتخاب کنید، تصمیم را بنویسید و تست کنید؛ و با یک codebase بگویید کدام الگوها واقعاً کار میکنند و کدام اسمها فقط تزییناند.
این صفحه فصل عملی گروه الگوهای طراحی است. فرض میکند فهرست الگوها را دیدهاید: نمای کلی خانوادهها در Design Patterns: Origin and the Three Families است و خود الگوها در Creational، Structural و Behavioral. اینجا هیچ الگویی را از نو درس نمیدهیم؛ از آنها استفاده میکنیم. همسایههای مفید: Code Smells and Refactoring (بوهایی که الگو را صدا میزنند)، صفحههای SOLID (OCP، DIP، SRP)، Composition and the Law of Demeter، Design Quality Principles، Data Persistence in Design و Distribution of Components.
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| همهٔ واژگان در چند جدول | همهچیز در یک دقیقه |
| چرا «فقط الگو بزن» شکست میخورد | چرا این فصل وجود دارد |
| ریشهها، با منبع | از کجا آمده |
| مسئله، نیروها، نامزدها، پیامدها، سادهترین | روش انتخاب الگو |
| Factory + Strategy، Decorator + Chain، Command + Memento و بقیه | ترکیبهای پرتکرار |
| checkout، اعلان، افزونه، قواعد، گزارش | زبان الگو برای هر دامنه |
| کتابخانهٔ استاندارد Go و هستهٔ Laravel، با مسیر فایل | خواندن کد متنباز |
| YAGNI، عمومیتدهی حدسی، نشانههای بیشطراحی | چگالی الگو |
| Replace conditional with strategy، Form template method | Refactoring به الگو |
| سوءاستفاده از Singleton، انفجار Factory، Strategy بیخون، Mediator خدا | ضدالگوها در استفادهٔ الگو |
| Gateway، ACL، Sidecar، Saga، Outbox، CQRS | الگوها در مقیاس سرویس |
| الگوی فریمورک در برابر الگوی اپلیکیشن | فریمورک در برابر اپلیکیشن |
| ADR، نامگذاری، تست | مستندسازی، تست |
| چه چیزی از انتقال به میکروسرویس جان سالم به در میبرد | مهاجرت یک feature |
| یک طراحی کامل با تست و دفتر تصمیم | مطالعهٔ موردی: موتور قیمت |
| باورهای غلط، چکیده، خودآزمایی، همهٔ اصطلاحها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
واژگان. هر ردیف بعداً باز میشود.
| اصطلاح | به زبان ساده | مثال کوچک | بدون آن چه خراب میشود |
|---|---|---|---|
| نیرو (Force) | فشاری که طراحی را به یک سو میکشد | «بازاریابی هر ماه یک تخفیف اضافه میکند» | الگو را برای نیرویی انتخاب میکنید که وجود ندارد |
| پیامد (Consequence) | هزینهای که بعد از پذیرش الگو میپردازید | Strategy برای هر حالت یک کلاس اضافه میکند | فقط فایدهها را میشمارید |
| الگوی نامزد (Candidate pattern) | یکی از دو یا سه پاسخ ممکن به همان نیروها | Strategy یا یک map ساده | عاشق اولین ایده میشوید |
| سادهترین گزینهٔ کارآمد (Simplest that works) | گزینهای با کمترین قطعهٔ متحرک که تغییر قابلانتظار را جذب کند | switch برای دو حالت | interface پیش از حالت دوم پیدا میشود |
| ترکیب الگو (Pattern combination) | دو الگو که هرکدام نیمی از مسئله را حل میکنند | Factory + Strategy | جفتی را از نو میسازید که فریمورک دارد |
| زبان الگو (Pattern language) | مجموعهای از الگوها که برای یک دامنه جور میشوند | Checkout: Pipeline، Strategy، Specification | الگوهای تکیانتخابشده کنار هم نمینشینند |
| چگالی الگو (Pattern density) | تعداد نقشهای الگو بهازای واحد رفتار | ۹ کلاس برای ۳۰ خط منطق | کسی نمیداند کار واقعی کجاست |
| عمومیتدهی حدسی (Speculative generality) | قلاب و انتزاعِ «شاید لازم شد» | interface با یک پیادهسازی | هزینهٔ نگهداری بدون سود |
| ضدالگو در استفادهٔ الگو | اسم یا شکل الگو بدون فایدهاش | OrderFactory که فقط new صدا میزند | تشریفات و اعتمادبهنفس کاذب |
| ADR | سندی یکصفحهای از یک تصمیم و پیامدهایش | «برای قواعد تخفیف Strategy داریم» | نفر بعدی کورکورانه برش میگرداند |
| الگوی فریمورک | الگویی که فریمورک میدهد و نگه میدارد | Manager::extend() در Laravel | چیزی را از نو میسازید که هست |
| الگوی اپلیکیشن | الگویی که برای دامنهٔ خودتان اضافه میکنید | Specification برای شرطهای تخفیف | سراغ قلابی میروید که جور نیست |
روش انتخاب در هفت پرسش.
| گام | پرسش | خروجی |
|---|---|---|
| ۱ | مسئله در یک جمله و بدون نام الگو چیست؟ | شرح مسئله |
| ۲ | نیروها چیست: چه چیزی تغییر میکند، چه کسی، هر چند وقت؟ | فهرست نیروها |
| ۳ | آیا کد ساده (تابع، switch، map، struct) برای نیروهای امروز کافی است؟ | توقف، یا ادامه |
| ۴ | کدام دو یا سه الگو میتوانند به این نیروها جواب بدهند؟ | نامزدها |
| ۵ | هر نامزد چه هزینهای دارد: کلاس، indirection، تلاش تست، واژگان تیم؟ | جدول پیامدها |
| ۶ | کدام سادهترین گزینه برای تغییر بعدیِ قابلنامبردن است؟ | انتخاب |
| ۷ | کجا ثبتش کنیم و چه چیزی باید ما را به بازبینی برگرداند؟ | ADR، محرک بازبینی |
هفت ترکیب. هرکدام در ترکیبهای پرتکرار باز میشود.
| جفت | پرسشی که جفت جواب میدهد | کجا قبلاً استفادهاش کردهاید |
|---|---|---|
| Factory + Strategy | کدام الگوریتم، با نام یا config | Manager::driver() در Laravel، map از funcها در Go |
| Decorator + Chain of Responsibility | رفتار را دور یک فراخوانی لایهلایه کن، با امکان توقف | middleware در http.Handler در Go، Pipeline در Laravel |
| Command + Memento | Undo، Redo، ممیزی | ویرایشگرها، صفحههای ویرایش گروهی، جبران Saga |
| Observer + Mediator | به واقعیتها واکنش نشان بده بیآنکه بدانی چه کسی واکنش دارد | Event::listen در Laravel، event bus دامنه |
| Composite + Visitor | یک درخت، چند عملیات | درخت فایل، AST، گروههای قاعدهٔ تخفیف |
| Builder + Director | ساخت گامبهگام بهعلاوهٔ دستورپختهای نامدار | query builder بهعلاوهٔ دستورپخت «درآمد ماهانه» |
| Proxy + Flyweight | شیء تنبل، مشترک و تغییرناپذیر | جستوجوی کششده، کلاینت راهدور با handle مشترک |
هر خانواده در ابزار شما کجاست.
| ایده | Go | Laravel |
|---|---|---|
| Strategy | یک interface یا نوع func، map بر پایهٔ نام | یک contract بستهشده در container، driverهای Manager |
| Decorator و زنجیره | func(http.Handler) http.Handler | Pipeline، middleware در HTTP |
| Observer | فهرست callback، channel | Event::listen، observerهای مدل |
| Adapter | http.HandlerFunc | adapterهای Flysystem پشت Storage |
| Factory | تابع سازنده، map از سازندهها | Container::make، Manager::createXxxDriver |
| Specification | مجموعهٔ ترکیبگرهای func(Cart) bool | چند کلاس کوچک، یا scopeهای Eloquent برای قواعد سمت پایگاهداده |
چرا این فصل وجود دارد
فهرست ۲۳ الگو میگوید هر الگو چیست. نمیگوید کی باید سراغ یکی رفت، کدام ترکیبها عادیاند، یا کجا باید ایستاد. شکست معمول این نیست که کسی الگو نمیشناسد؛ این است که الگو را تزیینی و از روز اول، پیش از وجود حالت دوم، به کار میبرند. نقلقول Fowler در بالا همین هشدار در زبان XP است: برای تغییری بسازید که میتوانید اسمش را ببرید، نه تغییری که میتوانید تصورش کنید.
| الگواول (تله) | مسئلهاول (این فصل) |
|---|---|
| «اینجا کجا Strategy بگذارم؟» | «اینجا چه چیزی تغییر میکند و چه کسی تغییرش میدهد؟» |
| interface از روز اول | کد ساده در روز اول، seam وقتی حالت دوم آمد |
| یک الگو برای هر مسئله | زبان کوچکی از دو یا سه الگو |
| اسمهای قرضگرفته از فهرست | اسمهای قرضگرفته از دامنه |
| طراحی با شمارش الگو بازبینی میشود | طراحی با هزینهٔ تغییر و هزینهٔ تست بازبینی میشود |
| تصمیم در ذهن یک نفر است | تصمیم در یک ADR یکصفحهای است |
شکل، روش انتخاب را بهصورت یک حلقه نشان میدهد. توجه کنید «آیا کد ساده کافی است؟» قبل از هر فهرست نامزد میآید، و گام آخر به نیروها برمیگردد: الگو پاسخ به یک وضعیت است و وقتی وضعیت عوض شد، انتخاب دوباره باز میشود.
تشبیهی که در این صفحه تکرار میکنیم: کشوی ابزار آشپزخانه. آشپز یک برشدهندهٔ آووکادو، یک مَندولین، یک پرس سیر و یک چاقوی خوب دارد. بیشتر غذاها چاقو میخواهند. برشدهندهٔ آووکادو برای روزی است که چهل آووکادو داری. آشپزخانهای که هر غذا را با ابزار دیگری میبرد کندتر است، تمیزکردنش سخت است و آشپز تازهوارد یادگرفتنش را نمیتواند. الگوها ابزارند و نیروها غذا.
سه بدفهمی رایج، از همین ابتدا
- «الگوی بیشتر یعنی طراحی بهتر.» کیفیت با ارزانیِ ورود تغییر بعدی و ارزانیِ تست سنجیده میشود، نه با تعداد اسم الگو در فهرست کلاسها.
- «الگو یک نمودار کلاس است که باید کپی شود.» الگو شکل راهحل برای یک مسئله در یک زمینه است، با پیامدهایش. همین الگو در Go یک نوع func است، در Laravel یک binding برچسبدار و در Java یک سلسلهمراتب کلاس.
- «اگر الگو نزنم بد طراحی میکنم.» یک
switchبا دو حالت اغلب بهترین طراحی است. الگو وقتی درست میشود که نیروها پیدا شوند.
از کجا آمده
زبانهای الگو (Pattern Languages)، دههٔ ۱۹۷۰. اینکه مجموعهای از الگوها بتواند یک «زبان» بسازد از معمار Christopher Alexander آمده است. برای این صفحه کتابهای Alexander را نخواندیم؛ پیوند او با نرمافزار را در صفحهای دیدیم که ADR را معرفی کرد و آن را خواندیم: میگوید پیامدهای یک ADR "become the context for subsequent ADRs" و آن را "similar to Alexander's idea of a pattern language: the large-scale responses create spaces for the smaller scale to fit into" مینامد (Michael Nygard، Documenting Architecture Decisions، ۲۰۱۱). معنای ما همین است: الگویی که اول انتخاب میکنید جا را برای بعدی باز میکند.
Gamma، Helm، Johnson، Vlissides، ۱۹۹۴. کتاب Design Patterns (معروف به «Gang of Four» یا GoF) ۲۳ الگو را در سه خانواده فهرست کرد. خود کتاب را برای این فصل نخواندیم؛ از صفحههای فهرست refactoring.guru استفاده کردیم که همان نیتها را میگویند. نمونه: "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).
Evans و Fowler، Specifications. مقالهٔ Eric Evans و Martin Fowler ایدهای را میدهد که در مطالعهٔ موردی به کار میبریم: "The central idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched against."
Kerievsky، ۲۰۰۴. کتاب Refactoring to Patterns از Joshua Kerievsky پرسش را برعکس کرد: بهجای طراحی با الگو از پیش، از کد کارکن با refactoringهای کوچک به الگو میرسید (ما فهرست آنلاین ۲۷ refactoring را در سایت Industrial Logic خواندیم، نه کتاب را). فهرست هر حرکت را با «مسئله» و «راهحل» میگوید. نمونه: "Problem: Conditional logic in a method controls which of several variants of a calculation are executed. Solution: Create a Strategy for each variant and make the method delegate the calculation to a Strategy instance." (Industrial Logic، Replace Conditional Logic with Strategy).
Fowler، Yagni، ۲۰۱۵. این نوشته «ویژگی حدسی» (Presumptive feature) را از ویژگی واقعی جدا میکند و چهار هزینهٔ ساختن زودهنگام را نام میبرد: هزینهٔ ساخت (Cost of build)، هزینهٔ تأخیر (Cost of delay)، هزینهٔ نگهداری (Cost of carry) که "this complexity makes it harder to modify and debug that software, thus increasing the cost of other features" و هزینهٔ ترمیم (Cost of repair). همچنین از Kohavi و همکاران نرخ پایه میآورد: "only ⅓ of them improved the metrics they were designed to improve."
Nygard، ۲۰۱۱. Documenting Architecture Decisions شکل ADR را میدهد: عنوان، زمینه، تصمیم، وضعیت، پیامدها؛ "The whole document should be one or two pages long." و "Agile methods are not opposed to documentation, only to valueless documentation."
الگوهای سطح سرویس. Eric Evans لایهٔ ضدفساد (Anti-Corruption Layer) را توصیف کرد؛ Microsoft Azure Architecture Center خلاصهاش میکند: "Implement a facade or adapter layer between different subsystems that don't share the same semantics." سایت microservices.io از Chris Richardson، Saga را "a reliably coordinated sequence of local transactions" و Outbox را ذخیرهٔ پیام "in the database as part of the transaction that updates the business entities" تعریف میکند. صفحهٔ CQRS از Fowler هشدار میدهد: "for most systems CQRS adds risky complexity." صفحهٔ Strangler Fig او (بهروزشده ۲۲ اوت ۲۰۲۴) جایگزینی تدریجی سیستم قدیمی را توصیف میکند.
مفهومها، یکییکی
هر بلوک همین ترتیب را دارد: به زبان ساده، باور غلط رایج، تعریف دقیق، خط زمانی، سناریوهای واقعی و راهحل.
روش انتخاب الگو (Pattern selection method) حیاتی
به زبان ساده: از مسئله و نیروها شروع کنید، دو یا سه راه پاسخ را بنویسید، هزینهٔ هرکدام را مقایسه کنید و آن را بردارید که کمترین قطعهٔ متحرک را دارد و هنوز تغییر بعدیِ قابلنامبردن را جذب میکند.
بدفهمی رایج: «انتخاب یعنی پیدا کردن الگویی که با مسئلهام جور است.» جستوجو در فهرست الگویی را پیدا میکند که نیتش شبیه مسئلهٔ شماست. تصمیم به نیروهایی بستگی دارد که فهرست نمیبیند: اندازهٔ تیم، ریتم انتشار، تعداد حالتهای امروز، صاحب هر حالت.
تعریف: روش یک زنجیرهٔ پنجبخشی است: مسئله (یک جمله، بدون نام الگو) ← نیروها (چه چیزی تغییر میکند، چه کسی، هر چند وقت، چه چیزی باید ثابت بماند) ← الگوهای نامزد (دو یا سه، از جمله «کد ساده») ← پیامدها (کلاس اضافه، indirection، تلاش تست، واژگانی که تیم باید بداند) ← سادهترین گزینهٔ کارآمد (نامزدی با کمترین قطعه که تغییر نامبردهشدهٔ بعدی را جذب کند).
Step Who / what Output
1 W1 Product: "VIP gets 15%" Problem: discount depends on customer kind
2 W1 Dev: 1 variant, 1 team Force list: low variance today; money, so must be exact
3 W1 Dev: plain code enough? Yes: one function with a switch, a test table
4 W5 Product: "loyal: 1% per year" Forces change: 3 variants, still one team
5 W5 Dev: candidates switch, map of funcs, Strategy interface
6 W5 Dev: consequences map of funcs: 1 file, no new types; interface: 1 type per variant
7 W5 Choice map of funcs; ADR-0003 records why not interface yet
8 W12 Partner team adds kinds Forces change: second team => interface + registryسناریوهای واقعی: تابع تخفیفی که از دو به شش حالت میرسد (map از funcها، بعد Strategy)؛ سرویس اعلانی که کانال دوم میگیرد (switch هنوز خوب است) و کانال پنجم (Manager با driverها)؛ endpoint خروجی که فقط CSV دارد (تابع ساده) و بعد PDF و XLSX (Template Method یا Strategy، بسته به اینکه چه کسی فرمت اضافه میکند).
| وضعیت | نامزدهای معمول | معمولاً کافی |
|---|---|---|
| یک حالت، بدون حالت دوم معلوم | تابع ساده | همان تابع |
| دو حالت، یک تیم، پایدار | if، switch، map | map از funcها |
| سه حالت یا بیشتر، یک تیم | map، Strategy | Strategy پشت یک تابع factory |
| حالتها را تیمها یا بستههای دیگر اضافه میکنند | Strategy + registry، افزونه | registry با extend() |
| حالتها در درخت ترکیب میشوند | Composite | Composite + Specification |
| رفتار باید دور رفتار دیگر بپیچد | Decorator، middleware | زنجیرهٔ decoratorها |
| واکنش به واقعیتها، واکنشدهندههای نامعلوم | Observer، event bus | رویداد دامنه + listenerها |
راهحل وقتی زود انتخاب کردهاید: interface را inline کنید (Collapse Hierarchy، Inline Class)، تستها را نگه دارید و منتظر حالت بعدی بمانید. چگالی الگو را ببینید.
ترکیبهای پرتکرار (Pattern combinations) حیاتی
به زبان ساده: بیشتر طراحیهای واقعی الگوها را جفتجفت به کار میبرند، چون یک الگو تصمیم میگیرد چه چیزی تغییر میکند و دیگری تصمیم میگیرد قطعهها چطور به هم وصل شوند.
بدفهمی رایج: «یک جفت الگو دو برابر طراحی است.» جفتِ خوب طراحیِ کمتری از هر کدام بهتنهایی میخواهد: الگوی دوم تشریفاتی را که اولی تحمیل میکرد برمیدارد.
تعریف: ترکیب دو یا چند الگوست که نقشهایشان درهم قفل میشود: یک شیء در هر دو نقش دارد. هفتا را میگوییم که تقریباً در هر codebase هستند.
| جفت | نقشها | چرا جور میشوند | snippet در Go | snippet در Laravel |
|---|---|---|---|---|
| Factory + Strategy | Factory انتخاب میکند، Strategy محاسبه | فراخواننده حالت را نام میبرد، نه نوع مشخص را | combos/factorystrategy | Manager::driver() |
| Decorator + Chain of Responsibility | هر decorator بعدی را میپیچد؛ هرکدام میتواند متوقف کند | رفتار مقطعی را به هر ترتیب لایه کن | combos/decoratorchain | Pipeline |
| Command + Memento | Command انجام و برگشت میدهد؛ Memento بازمیگرداند | Undo بدون معکوسِ ارزان برای هر دستور | combos/commandmemento | CommandMemento.php |
| Observer + Mediator | Mediator اشتراکها را دارد؛ observerها واکنش میدهند | اجزا هرگز به هم ارجاع نمیدهند | combos/observermediator | Event::listen |
| Composite + Visitor | Composite درخت است؛ Visitor یک عملیات | عملیات تازه بدون ویرایش گرهها | combos/compositevisitor | CompositeVisitor.php |
| Builder + Director | Builder گام دارد؛ Director دستورپخت | دستورپختها قابلاستفادهٔ مجدد و نامدارند | combos/builderdirector | query builder + دستورپخت |
| Proxy + Flyweight | Proxy تنبل بار میکند؛ Flyweight به اشتراک میگذارد | یک شیء گران و تغییرناپذیر بهازای هر کلید | combos/proxyflyweight | Cache + شیء مشترک |
Request Layer What happens (Decorator + Chain)
1 GET /pay Recover defer recover(); calls next
2 RequireToken("s3cret") header missing -> 401, chain stops here
3 handler never reached
4 GET /pay Recover calls next
5 +token RequireToken header ok -> calls next
6 handler panics -> Recover turns it into 500سناریوهای واقعی: middleware در HTTP (Decorator + Chain) در هر دو پشته؛ ویرایشگر متن یا صفحهگسترده با Undo (Command + Memento)؛ رویدادهای دامنهٔ Laravel با چند listener (Observer + Mediator)؛ درخت فایل مدیریتی که باید حجم کل، دسترسیها و جستوجو نشان بدهد (Composite + Visitor)؛ endpointهای گزارش با دستورپختهای نامدار (Builder + Director)؛ کش glyph یا ارز (Proxy + Flyweight).
راهحل در Go (Factory + Strategy و Decorator + Chain):
// Package factorystrategy combines Factory and Strategy: the factory picks the strategy by name.
package factorystrategy
import "fmt"
// Shipper is the Strategy.
type Shipper interface{ Cost(weightGrams int) int64 }
type flat int64
func (f flat) Cost(int) int64 { return int64(f) }
type perKilo int64
func (p perKilo) Cost(w int) int64 { return int64(p) * int64((w+999)/1000) }
var registry = map[string]func() Shipper{
"standard": func() Shipper { return flat(500) },
"heavy": func() Shipper { return perKilo(300) },
}
// New is the Factory: the only place that knows concrete types.
func New(name string) (Shipper, error) {
mk, ok := registry[name]
if !ok {
return nil, fmt.Errorf("no shipper %q", name)
}
return mk(), nil
}// Package decoratorchain combines Decorator and Chain of Responsibility: each middleware wraps the next handler.
package decoratorchain
import (
"log"
"net/http"
)
// Middleware is a Decorator of http.Handler.
type Middleware func(http.Handler) http.Handler
// Chain builds the chain: the first middleware is the outermost one.
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// Recover turns a panic into a 500 (one link of the chain).
func Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
log.Printf("panic: %v", v)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
// RequireToken may stop the chain (the "responsibility" part): it does not call next.
func RequireToken(token string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+token {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}راهحل در Laravel (Factory + Strategy به شکل Manager، Decorator + Chain به شکل Pipeline):
<?php
// Factory + Strategy in Laravel: Support\Manager is exactly this pair. getDefaultDriver() picks the strategy,
// createXxxDriver() is the factory method, extend() lets other packages add strategies.
namespace App\Shipping;
use Illuminate\Support\Manager;
interface Shipper
{
public function cost(int $weightGrams): int;
}
final class ShippingManager extends Manager
{
public function getDefaultDriver(): string
{
return $this->config->get('shipping.default', 'standard');
}
protected function createStandardDriver(): Shipper
{
return new class implements Shipper {
public function cost(int $weightGrams): int { return 500; }
};
}
protected function createHeavyDriver(): Shipper
{
return new class implements Shipper {
public function cost(int $weightGrams): int { return 300 * (int) ceil($weightGrams / 1000); }
};
}
}
// Usage: app(ShippingManager::class)->driver('heavy')->cost(2500); // 900
// Extension from another package: app(ShippingManager::class)->extend('drone', fn ($app) => new DroneShipper());<?php
// Decorator + Chain of Responsibility in Laravel: Pipeline wraps the destination in one closure per pipe.
namespace App\Checkout;
use Closure;
use Illuminate\Support\Facades\Pipeline;
final class ValidateStock
{
public function handle(CheckoutContext $ctx, Closure $next): mixed
{
if (! $ctx->stockOk) {
return $ctx->fail('out of stock'); // stops the chain: the "responsibility" part
}
return $next($ctx); // delegates to the next decorator
}
}
final class ApplyDiscounts
{
public function __construct(private \App\Pricing\PricingEngine $engine) {}
public function handle(CheckoutContext $ctx, Closure $next): mixed
{
$ctx->quote = $this->engine->price($ctx->cart);
return $next($ctx);
}
}
final class CheckoutContext
{
public ?\App\Pricing\Quote $quote = null;
public ?string $error = null;
public function __construct(public \App\Pricing\Cart $cart, public bool $stockOk = true) {}
public function fail(string $why): self
{
$this->error = $why;
return $this;
}
}
// Pipeline resolves class-string pipes from the container, so constructor injection works.
function checkout(CheckoutContext $ctx): CheckoutContext
{
return Pipeline::send($ctx)
->through([ValidateStock::class, ApplyDiscounts::class])
->thenReturn();
}پنج جفت دیگر همین شکل را دارند و در پوشههای snippet هستند (آزمایشگاه اجرایشان میکند). کد Go آنها combos/commandmemento، combos/observermediator، combos/compositevisitor، combos/builderdirector و combos/proxyflyweight است؛ نسخههای Laravel: CommandMemento.php، ObserverMediator.php، CompositeVisitor.php، BuilderDirector.php و ProxyFlyweight.php.
زبان الگو برای هر دامنه (Pattern languages) حیاتی
به زبان ساده: در یک دامنه همان چند الگو بارها پیدا میشوند و با هم جور میشوند. برای دامنههایی که کار میکنید همان چند تا را یاد بگیرید.
بدفهمی رایج: «برای هر کلاس جدا بهترین الگو را انتخاب کن.» الگوهایی که تکتک انتخاب شوند اغلب با هم میجنگند؛ زبان یکجا انتخاب میشود تا هر پاسخ جا برای بعدی باز کند.
تعریف: زبان الگو مجموعهٔ کوچکی از الگوهاست، با ترتیبِ بهکارگیری، برای یک نوع مسئله. زبانهای پایین عادتهای کاری ما هستند، نه استاندارد منتشرشده؛ جفتهای داخلشان از فهرست الگوها میآیند.
| دامنه | زبان الگو (به همین ترتیب) | چرا این ترتیب |
|---|---|---|
| checkout تجارت الکترونیک | Pipeline (Chain) ← Strategy (قیمت، حمل، پرداخت) ← Specification (واجد شرایط بودن) ← Command (ثبت سفارش) ← Observer (رویدادهای بعد از سفارش) ← Outbox (انتشار مطمئن) | اول گامها، بعد الگوریتمهای متغیر داخل گامها، بعد واکنشها بعد از commit |
| سیستم اعلان | Strategy (کانال) ← Factory یا Manager (انتخاب کانال) ← Template Method (اسکلت پیام) ← Decorator (محدودسازی نرخ، retry) ← Observer (محرک) | کانالها بیشترین تغییر را دارند؛ سیاستها دورشان میپیچند |
| سیستم افزونه | Registry + Factory ← Strategy (قرارداد افزونه) ← Adapter (شکلهای شخص ثالث) ← Facade (API میزبان) ← Observer (قلابها) | میزبان قرارداد را دارد؛ افزونهها به نقطههای نامدار وصل میشوند |
| موتور قواعد | Specification (شرطها) ← Strategy (کنشها) ← Composite (گروه قواعد) ← Interpreter یا Factory دادهمحور (بارگذاری از ذخیره) ← Chain (ترتیب) | شرط و کنش دو محور جدا هستند؛ درخت از ترکیب میآید |
| تولید گزارش | Builder (گامها) ← Director (دستورپختها) ← Template Method (اسکلت ثابت) ← Strategy (قالب) ← Visitor (عملیات روی درخت داده) | اول ساخت، بعد قالبها و عملیات |
Step Checkout stage Pattern in use Force that chose it
1 1 Validate stock Chain of Responsibility Steps change order, some stop the flow
2 2 Price the cart Strategy + Composite Rules vary by campaign, combine in groups
3 3 Eligibility of a rule Specification Conditions combine: segment and window and total
4 4 Place the order Command Retry, audit, idempotency key
5 5 Tell the world Observer (after commit) Mail, stock, analytics must not block the order
6 6 Reliable publication Outbox Event must exist if and only if the order doesسناریوهای واقعی: مطالعهٔ موردی پایین گام قیمتگذاری از زبان checkout است؛ سیستم اعلان خود Laravel همان زبان اعلان در ۲۰۰ خط است (ChannelManager از Manager ارث میبرد)؛ Flysystem بهعلاوهٔ Storage در Laravel زبان افزونه با adapterهاست.
راهحل وقتی زبان جور نیست: اگر به الگویی بیرون از زبان نیاز دارید، ببینید نیروها واقعاً فرق دارند؛ معمولاً یکی از انتخابهای قبلی خیلی کوچک بوده.
خواندن کد متنباز برای دیدن الگوها (Reading open-source code) حیاتی
به زبان ساده: سریعترین راه برای فهمیدن اینکه الگو کی ارزشش را دارد، خواندن کدی است که الگو در آن پولش را درآورده. کتابخانهٔ استاندارد و فریمورکی که هر روز به کار میبرید پر از آن است.
بدفهمی رایج: «کد فریمورک برای خواندن خیلی پیشرفته است.» بیشتر این کلاسها ۱۰۰ تا ۴۰۰ خطاند و commentهایی دارند که انتخاب را توضیح میدهند.
تعریف: خواندن برای الگو یعنی فایل را باز کنید، نقش هر نوع را (نه اسم کلاس که ممکن است دروغ بگوید) بنویسید و بپرسید الگو به چه نیرویی خدمت میکند.
Step Action What you learn
1 1 Open Support/Manager.php getDefaultDriver(), createDriver(), extend(): Factory + Strategy
2 2 Open Notifications/ChannelManager.php extends Manager: one 200-line file is the whole channel registry
3 3 Search for 'extends Manager' Cache, Mail, Auth, Filesystem, Notifications share the shape
4 4 Open Pipeline/Pipeline.php, then() array_reduce over pipes builds nested closures: Decorator chain
5 5 Open net/http/server.go, HandlerFunc A func type with one method: Adapterکتابخانهٔ استاندارد Go (از مخزن Go در GitHub، مسیرهای src/):
| فایل | الگویی که میبینید | نقش نوعها |
|---|---|---|
src/net/http/server.go | Strategy، Adapter، Decorator | interface به نام Handler؛ HandlerFunc ("an adapter to allow the use of ordinary functions as HTTP handlers")؛ StripPrefix و TimeoutHandler یک Handler را میپیچند |
src/net/http/server.go | Registry، Mediator | ServeMux الگوها را به handlerها نگاشت میکند و dispatch میکند |
src/io/io.go | Decorator | TeeReader و LimitReader یک Reader را میپیچند و Reader برمیگردانند |
src/sort/sort.go | Strategy | sort.Interface (شامل Len، Less، Swap) استراتژی sort.Sort است |
src/database/sql/driver/driver.go | Abstract Factory، Bridge | Driver، Connector، Conn قرارداد بین database/sql و یک driver هستند |
فریمورک Laravel (شاخهٔ 13.x، مسیرهای src/Illuminate/):
| فایل | الگویی که میبینید | به چه نگاه کنید |
|---|---|---|
Container/Container.php | Factory، Registry، Decorator | bind، singleton، make، build؛ extend() یک شیء حلشده را میپیچد؛ when() یک ContextualBindingBuilder (Builder) برمیگرداند؛ tag() و tagged() strategyها را گروه میکنند |
Pipeline/Pipeline.php | Chain + Decorator | then() روی pipeهای برعکسشده array_reduce با carry() اجرا میکند؛ هر pipe مقدار و یک closure به نام $next میگیرد |
Events/Dispatcher.php | Observer، Mediator | Event dispatcher: listen، dispatch، until (توقف در اولین پاسخ)، createClassListener عبارت Class@method را به closure تبدیل میکند |
Database/Query/Builder.php | Builder، Composite، Strategy | فراخوانیهای روان where؛ forNestedWhere() و addNestedWhereQuery() گروهها را تودرتو میکنند (Composite)؛ $grammar برای هر پایگاهداده SQL میسازد (Strategy)؛ toSql() |
Notifications/ChannelManager.php | Factory + Strategy | class ChannelManager extends Manager؛ channel($name) یک driver میدهد؛ send و sendNow |
Support/Manager.php | Factory + Strategy + Registry | createDriver() اول customCreators، بعد متد createXxxDriver را امتحان میکند و وگرنه خطا میدهد؛ extend() یک creator ثبت میکند |
Filesystem/FilesystemManager.php | Adapter، Factory | disk()، build()، createLocalDriver()، createS3Driver() adapterهای League Flysystem را پشت یک API میپیچند |
Support/Facades/Pipeline.php | Facade | یک رخ ایستا (send، through، then، thenReturn) روی pipeline |
مستندات Laravel دربارهٔ storage همین را میگوید: "Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem PHP package by Frank de Jonge." این جمله یک توصیف الگوست: لایهٔ adapter روی یک کتابخانهٔ شخص ثالث.
راهحل: یک فایل را چطور برای الگو بخوانیم: متدهای عمومی را فهرست کنید، نوعهای یکمتدی را علامت بزنید، جایی را که نمونهها ساخته میشوند پیدا کنید و کنار اسم کلاسها نام نقش را بنویسید.
چگالی الگو و نشانههای بیشطراحی (Pattern density) مهم
به زبان ساده: چگالی یعنی بهازای هر واحد رفتار چقدر ساختار حمل میکنید. کمی ساختار بیمهٔ ارزان است؛ زیادش مالیاتی روی هر تغییر.
بدفهمی رایج: «انتزاع مجانی است چون فقط interface است.» هر interface یک فایل، یک اسم برای یادآوری، یک indirection در هر stack trace و یک mock در هر تست اضافه میکند. «هزینهٔ نگهداری» (Cost of carry) Fowler همین است: کد "adds some complexity to the software, this complexity makes it harder to modify and debug that software, thus increasing the cost of other features."
تعریف: YAGNI ("You Aren't Gonna Need It") میگوید قابلیتی را که فرض میکنید بعداً لازم میشود نسازید. عمومیتدهی حدسی (Speculative generality) بویی است که YAGNI هدفش میگیرد؛ refactoring.guru آن را کدی میداند که "is created 'just in case' to support anticipated future features that never get implemented. As a result, code becomes hard to understand and support." درمانهایی که میآورد: Collapse Hierarchy، Inline Class، Inline Method، Remove Parameter. همچنین میگوید کی نادیدهاش بگیرید: کد فریمورکی که هنوز کاربرانش معلوم نیستند.
Signal Check Likely cure
1 One implementation per interface grep "implements X" shows 1 Inline the interface
2 Class names end in Manager/Helper/Impl count them per package Rename by role or delete
3 Factory whose body is `new T(...)` read the body Call the constructor
4 Strategy with one strategy list the strategies Plain function
5 Parameters nobody passes grep call sites Remove Parameter
6 Mediator with a switch on event names count cases Split by area, or events
7 Pattern name in a class, none in domain ask "which force?" Rename or remove| نشانه | چرا آسیب میزند | نشانهٔ مخالف (نگهش دارید) |
|---|---|---|
| یک پیادهسازی برای هر interface | فایل و mock و indirection اضافه | seam تست برای وابستگی کند (پایگاهداده، ساعت، HTTP) |
Manager، Helper، Util در اسمها | اسم دربارهٔ نقش چیزی نمیگوید | کلاس پایهای که فریمورک آن را نام گذاشته |
Factory دور new | سازنده را پنهان میکند | Factory که یک invariant را اعمال یا نوع را انتخاب میکند |
| لایههای زیاد در هر فراخوانی | stack traceها بلند میشوند | لایههایی که مرز واقعیاند (ماژول، پردازه) |
| config برای همهچیز | رفتار از بازبینی کد بیرون میرود | مقادیری که اپراتورها واقعاً عوض میکنند |
| «شاید بعداً لازم شد» | Fowler: احتمال مفید بودن پایین است | API منتشرشدهای که بعداً نمیشود عوضش کرد |
| هزینه (Fowler) | معنی در زمینهٔ الگو |
|---|---|
| هزینهٔ ساخت (Cost of build) | نوشتن interface، registry و تست برای حالتهایی که هرگز نمیآیند |
| هزینهٔ تأخیر (Cost of delay) | ویژگی واقعی که چون قلاب میساختید تحویل نشد |
| هزینهٔ نگهداری (Cost of carry) | هر تغییر بعدی از لایهٔ اضافه رد میشود |
| هزینهٔ ترمیم (Cost of repair) | انتزاعهای غلط باید باز شوند، معمولاً زیر فشار |
سناریوهای واقعی: interface مخزن (Repository) با یک پیادهسازی Eloquent و mock در همهجا (فقط اگر تستها واقعاً seam میخواهند نگهش دارید)؛ سیستم افزونه برای اپی که شخص ثالثی ندارد؛ تقسیم CQRS برای یک پنل CRUD.
راهحل: اندازه بگیرید (ببینید سازوکار)، تشریفات را حذف کنید، تستها را نگه دارید و یک comment بگذارید که محور تغییر را نام میبرد تا حالت بعدی ارزان باشد.
Refactoring به الگو (Refactoring to patterns) حیاتی
به زبان ساده: بهجای طراحیِ الگو از پیش، کد ساده بنویسید، منتظر فشار بمانید و با گامهای کوچک و امن، که تستها سبز میمانند، به سمت الگو بروید.
بدفهمی رایج: «Refactoring به الگو یعنی بازنویسی.» هر حرکت دنبالهای از گامهای مکانیکی است؛ در هر گام تستها پاس میشوند و کد قابل انتشار است.
تعریف: فهرست Kerievsky ۲۷ refactoring دارد (فهرست را در سایت Industrial Logic خواندیم): Chain Constructors، Compose Method، Encapsulate Classes With Factory، Encapsulate Composite With Builder، Extract Adapter، Extract Composite، Extract Parameter، Form Template Method، Inline Singleton، Introduce Null Object، Introduce Polymorphic Creation With Factory Method، Limit Instantiation With Singleton، Move Accumulation To Collecting Parameter، Move Accumulation To Visitor، Move Creation Knowledge To Factory، Move Embellishment To Decorator، Replace Conditional Dispatcher With Command، Replace Conditional Logic With Strategy، Replace Constructors With Creation Methods، Replace Hard-Coded Notifications With Observer، Replace Implicit Language With Interpreter، Replace Implicit Tree With Composite، Replace One/Many Distinctions With Composite، Replace State-Altering Conditionals with State، Replace Type Code With Class، Unify Interfaces With Adapter، Unify Interfaces.
| حرکت (Kerievsky) | مسئله بهروایت فهرست | بویی که جواب میدهد | شکل در Go یا Laravel |
|---|---|---|---|
| Replace Conditional Logic with Strategy | "Conditional logic in a method controls which of several variants of a calculation are executed." | دستورهای switch | map از funcها، کلاسهای برچسبخورده در container |
| Introduce Polymorphic Creation with Factory Method | "Classes in a hierarchy implement a method similarly except for an object creation step." | کد تکراری | تابع سازنده که بهعنوان پارامتر میآید، متد createXxx |
| Form Template Method | "Two methods in subclasses perform similar steps in the same order, yet the steps are different." | کد تکراری | Go: فیلد func یا embedding؛ PHP: کلاس پایهٔ abstract |
| Unify Interfaces with Adapter | "Clients interact with two classes, one of which has a preferred interface." | interfaceهای واگرا | نوع wrapper نازک، سبک HandlerFunc |
| Extract Composite | "Subclasses in a hierarchy implement the same Composite." | کد تکراری در زیرکلاسها | یک نوع Group با فرزندان |
Step Refactoring step (Replace Conditional with Strategy) Tests
1 1 Extract each case body into a function (Extract Method) green
2 2 Give the functions one signature green
3 3 Put them in a map keyed by the old case label green
4 4 Replace the switch with a lookup + call green
5 5 Make unknown keys an error, not a silent default red then green (new test)
6 6 Only now: promote the func type to an interface if state greenسناریوهای واقعی: switch تخفیف از جدول یکدقیقهای؛ switch وضعیت سفارش (Replace State-Altering Conditionals with State)؛ انبوه if (type == 'csv') در یک exporter (Form Template Method).
راهحل در Go (قبل و بعد):
// Package before is the starting point: one function, one growing switch.
package before
// Discount returns the discount in cents. Every new customer type edits this function.
func Discount(kind string, subtotal int64, years int) int64 {
switch kind {
case "regular":
return 0
case "vip":
return subtotal * 15 / 100
case "loyal":
pct := int64(years)
if pct > 10 {
pct = 10
}
return subtotal * pct / 100
case "staff":
return subtotal * 30 / 100
default:
return 0
}
}// Package after applies Replace Conditional Logic with Strategy, step by step.
package after
import "fmt"
// Customer carries the inputs the strategies need.
type Customer struct {
Kind string
Years int
}
// Discounter is the Strategy interface (the point of variation).
type Discounter interface {
Discount(c Customer, subtotal int64) int64
}
// DiscounterFunc adapts a function to Discounter.
type DiscounterFunc func(Customer, int64) int64
// Discount calls the function.
func (f DiscounterFunc) Discount(c Customer, s int64) int64 { return f(c, s) }
func percent(p int64) Discounter {
return DiscounterFunc(func(_ Customer, s int64) int64 { return s * p / 100 })
}
var strategies = map[string]Discounter{
"regular": percent(0),
"vip": percent(15),
"staff": percent(30),
"loyal": DiscounterFunc(func(c Customer, s int64) int64 {
return s * int64(min(c.Years, 10)) / 100
}),
}
// For is the creation point (Introduce Polymorphic Creation). An unknown kind is an error, not a silent zero.
func For(kind string) (Discounter, error) {
d, ok := strategies[kind]
if !ok {
return nil, fmt.Errorf("unknown customer kind %q", kind)
}
return d, nil
}راهحل در Laravel (همین حرکت با container):
<?php
// app/Services/CustomerDiscount.php — starting point: one growing match.
namespace App\Services;
final class CustomerDiscount
{
public function for(string $kind, int $subtotal, int $years): int
{
return match ($kind) {
'regular' => 0,
'vip' => intdiv($subtotal * 15, 100),
'loyal' => intdiv($subtotal * min($years, 10), 100),
'staff' => intdiv($subtotal * 30, 100),
default => 0, // a typo in $kind silently gives no discount
};
}
}<?php
// Replace Conditional Logic with Strategy: one class per variant, one place that creates them.
namespace App\Discounts;
use Illuminate\Container\Attributes\Tag;
use InvalidArgumentException;
interface Discounter
{
public function kind(): string;
public function discount(int $subtotal, int $years): int;
}
final class Vip implements Discounter
{
public function kind(): string { return 'vip'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * 15, 100); }
}
final class Loyal implements Discounter
{
public function kind(): string { return 'loyal'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * min($years, 10), 100); }
}
// Creation point: the container injects every class tagged 'discounters' (see the service provider below).
final class DiscounterFactory
{
/** @var array<string, Discounter> */
private array $byKind = [];
/** @param iterable<Discounter> $discounters */
public function __construct(#[Tag('discounters')] iterable $discounters)
{
foreach ($discounters as $d) {
$this->byKind[$d->kind()] = $d;
}
}
public function for(string $kind): Discounter
{
return $this->byKind[$kind] ?? throw new InvalidArgumentException("unknown customer kind [$kind]");
}
}
// app/Providers/AppServiceProvider.php::register()
// $this->app->tag([Vip::class, Loyal::class], 'discounters');
// A new customer kind is a new class plus one name in that list; DiscounterFactory never changes.ضدالگوها در استفادهٔ الگو (Anti-patterns in pattern use) مهم
به زبان ساده: اینها اشتباههاییاند که هنگام استفاده از الگو رخ میدهند: اسمش هست، فایدهاش نیست.
بدفهمی رایج: «اگر از نمودار GoF پیروی کند خوب است.» کلاسی به شکل نمودار که نیرویی پشتش نیست سربار است.
تعریف: ضدالگو در استفادهٔ الگو ساختاری است که شکل یا اسم یک الگو را قرض میگیرد و فایدهاش را برمیدارد، معمولاً با افزودن coupling پنهان یا تشریفات. فهرست گستردهتر بوها در Code Smells and Refactoring است.
| ضدالگو | نشانه | چرا رخ میدهد | درمان |
|---|---|---|---|
| سوءاستفاده از Singleton (Singleton abuse) | Settings::instance() یا یک DB سراسری که از همهجا خوانده میشود | راحتی؛ «فقط یکی هست» | وابستگی را پاس بدهید؛ container طول عمر را نگه دارد (DIP) |
| انفجار Factory (Factory explosion) | AbstractFooFactoryFactory، یک factory برای هر کلاس | factory از سر عادت | سازنده را صدا بزنید؛ برای هر انتخاب واقعی یک factory |
| interface برای همهچیز | IUserService با یک UserService | «به interface برنامه بنویس» بد فهمیده شده | interface جایی که پیادهسازی دوم یا seam تست هست |
| Strategy بیخون (Anemic strategy) | Strategy با یک بدنه و بدون state | OCP زودهنگام | تابع ساده؛ وقتی حالت دوم آمد استخراج کنید |
| Mediator خدا (God mediator) | یک کلاس با همهٔ قواعد همهٔ صفحهها یا رویدادها | Mediator منطق را میبلعد | یک mediator برای هر ناحیه؛ رویداد با listenerهای محلی |
| کلاسِ نامالگو بدون الگو | OrderFactory که فقط new Order میزند | نامگذاری تزیینی | بر پایهٔ نقش تغییر نام یا حذف |
| زنجیرهٔ Observer با ترتیب پنهان | listener A رویدادی میفرستد که B را راه میاندازد | رویداد بهجای جریان کنترل | هماهنگی صریح برای کار مرتب |
| پشتهٔ Decorator که کسی نمیتواند فهرستش کند | ترتیب رفتار به ترتیب ثبت بستگی دارد | پراکندگی middleware | یک زنجیرهٔ مستند، تست ترتیب |
| Visitor روی درخت ناپایدار | هر نوع گرهٔ جدید همهٔ visitorها را عوض میکند | Visitor برای محور اشتباه انتخاب شده | متد روی گرهها، یا یک نوع جمع بسته |
Step Event Smell it creates
1 1 Dev adds Settings::instance() for convenience Hidden global
2 2 Test needs different settings Static reset in setUp()
3 3 Second test file forgets the reset Order-dependent failures
4 4 Parallel test runner Flaky suite
5 5 Fix: inject Settings, drop the static Tests pass in any orderسناریوهای واقعی: اپ Laravel که همهٔ کلاسهایش Settings::instance() صدا میزنند؛ سرویس Go با var DB *sql.DB در سطح package؛ فرم UI که mediatorش به ۶۰ case میرسد.
راهحل در Go و Laravel:
// Package before collects four anti-patterns that wear a pattern's name.
package before
import "database/sql"
// 1. Singleton abuse: a hidden global every caller reaches for.
var DB *sql.DB
// OrderCount cannot be tested without a real database.
func OrderCount() (n int, err error) {
err = DB.QueryRow("SELECT count(*) FROM orders").Scan(&n)
return n, err
}
// 2. Pattern-named class with no pattern: a "factory" that is just a constructor with an extra word.
type Order struct{ ID string }
type OrderFactory struct{}
func (OrderFactory) CreateOrder(id string) *Order { return &Order{ID: id} }
// 3. Anemic strategy: an interface with one implementation, no second variant in sight.
type TaxStrategy interface{ Tax(net int64) int64 }
type FlatTaxStrategy struct{}
func (FlatTaxStrategy) Tax(net int64) int64 { return net * 20 / 100 }
// 4. God mediator: every rule of every screen lives in one switch.
type Mediator struct{ state map[string]string }
func (m *Mediator) Notify(sender, event string) {
switch sender + ":" + event {
case "country:changed":
m.state["state"] = ""
case "cart:changed":
m.state["total"] = "recomputed"
case "coupon:applied":
m.state["total"] = "recomputed"
m.state["banner"] = "shown"
}
}// Package after shows the plain versions that replace the four anti-patterns.
package after
import (
"context"
"database/sql"
)
// 1. Pass the dependency. The caller owns the lifetime; tests pass a fake.
type OrderCounter struct{ DB *sql.DB }
// Count runs the query on the injected handle.
func (o OrderCounter) Count(ctx context.Context) (n int, err error) {
err = o.DB.QueryRowContext(ctx, "SELECT count(*) FROM orders").Scan(&n)
return n, err
}
// 2. A struct literal is enough. Add a constructor only when it enforces an invariant.
type Order struct{ ID string }
// 3. One variant: a plain function. Introduce an interface when the second variant arrives.
func Tax(net int64) int64 { return net * 20 / 100 }
// 4. Small mediators, one per screen area, each with a narrow job.
type CartPanel struct{ Recompute func() }
// OnCouponApplied is a local reaction, not a branch in a global switch.
func (p CartPanel) OnCouponApplied() { p.Recompute() }<?php
// Four anti-patterns that wear a pattern's name.
namespace App\Smells;
use Illuminate\Support\Facades\DB;
// 1. Singleton abuse: a static accessor hides the dependency.
final class Settings
{
private static ?self $instance = null;
public array $values = [];
public static function instance(): self { return self::$instance ??= new self(); }
}
// 2. Pattern-named class with no pattern: a "factory" that only calls new.
final class OrderFactory
{
public function createOrder(array $data): Order { return new Order($data); }
}
// 3. Anemic strategy: an interface with one implementation and no second variant in sight.
interface TaxStrategy { public function tax(int $net): int; }
final class FlatTaxStrategy implements TaxStrategy
{
public function tax(int $net): int { return intdiv($net * 20, 100); }
}
// 4. God mediator: every rule of every screen in one switch.
final class FormMediator
{
public function notify(string $sender, string $event, array &$state): void
{
switch ("$sender:$event") {
case 'country:changed': $state['state'] = null; break;
case 'cart:changed': $state['total'] = 'recomputed'; break;
case 'coupon:applied': $state['total'] = 'recomputed'; $state['banner'] = 'shown'; break;
}
}
}<?php
// The plain versions that replace the four anti-patterns.
namespace App\Smells;
use Illuminate\Support\Facades\Config;
// 1. Use the framework's own singleton: config() / the container. Inject what the class really needs.
final readonly class TaxCalculator
{
public function __construct(private int $ratePercent) {}
// 3. One variant: a plain method. Extract an interface when the second variant arrives.
public function tax(int $net): int { return intdiv($net * $this->ratePercent, 100); }
}
// app/Providers/AppServiceProvider.php::register()
// $this->app->bind(TaxCalculator::class, fn () => new TaxCalculator(Config::integer('tax.rate_percent')));
// 2. A constructor is enough. Order's own constructor enforces its invariants.
// 4. Livewire/Alpine events or one small component per screen area replace the god mediator;
// the server side uses one listener per reaction (see the Event section of the page).الگوها در مقیاس سرویس (Patterns at service scale) حیاتی
به زبان ساده: الگوهای مشهور سطح سرویس همان ایدههای GoF هستند با یک شبکه در وسط. اگر Facade، Adapter، Proxy، Observer، Command و Mediator را بشناسید، شکل gateway، ACL، sidecar، outbox و saga را هم میشناسید؛ آنچه عوض میشود مدل شکست است.
بدفهمی رایج: «الگوهای سرویس موضوعی جدا از الگوهای طراحیاند.» همان ایدهها هستند، اما حالا هر فراخوانی میتواند timeout بخورد، تکرار شود یا دیر برسد، پس هر الگو به timeout، کلید idempotency یا جبران (Compensation) نیاز دارد.
تعریف: نگاشت زیر خوانش خودِ ماست (استنباط، نه از منابع). تعریفهای نقلشده از منبعیاند که در هر ردیف آمده.
| الگوی سطح سرویس | نزدیکترین ایدهٔ GoF | شبکه چه اضافه میکند | بیشتر بخوانید |
|---|---|---|---|
| API gateway | Facade + Proxy. Microsoft: "Route requests to multiple services or multiple service instances using a single endpoint." | احراز هویت، محدودیت نرخ، مسیریابی، شکست | API Gateway, BFF and Service Mesh |
| لایهٔ ضدفساد (Anti-corruption layer، ACL) | Adapter + Facade. "Implement a facade or adapter layer between different subsystems that don't share the same semantics." | DTO جدا برای سیم، نسخهبندی | Service boundaries |
| Sidecar | Decorator یا Proxy در پردازهٔ جدا. "Deploy application components into a process or container separate from the main application." | چرخهٔ عمر مشترک، یک hop اضافه | Microkernel and plugin |
| Transactional outbox | Observer پایدارشده. پیام را "in the database as part of the transaction that updates the business entities" ذخیره کن. | تحویل حداقل-یکبار، dedup | Outbox pattern |
| Saga | Command + State + Mediator. "a reliably coordinated sequence of local transactions" | جبران، شکست جزئی | Saga pattern |
| CQRS | Command و Query جدا. "for most systems CQRS adds risky complexity" (Fowler) | تأخیر مدل خواندن | Event Sourcing and CQRS |
| Circuit breaker | Proxy + State | حالت باز، نیمهباز، بسته | Circuit breaker |
| Idempotent consumer | Command + ذخیرهٔ dedup | تحویل حداقل-یکبار | Idempotent consumers and inbox |
| Strangler fig | Facade یا Proxy که بین قدیم و جدید مسیریابی میکند | دو سیستم همزمان | Monolith vs microservices vs modular |
Step Call (pricing as a service, gateway in front) Pattern at work
1 1 Client -> Gateway: POST /checkout Facade: one entry point
2 2 Gateway -> Checkout: auth passed, route Proxy: routing, rate limit
3 3 Checkout -> Pricing (Remote adapter): quote Proxy adapter: timeout 300 ms
4 4 Pricing: Engine.Price(cart) Strategy + Composite (inside)
5 5 Pricing unreachable Fallback: no-discount quote, logged
6 6 Checkout commits order + outbox row Outbox: one local transaction
7 7 Relay publishes OrderPlaced Observer across servicesسناریوهای واقعی: gateway یک فروشگاه اینترنتی؛ سرویس صورتحسابی که نام فیلدهای ERP قدیمی را پشت ACL ترجمه میکند؛ sidecar در service mesh برای mTLS؛ جریان سفارشی که پرداخت و موجودی را با saga میپوشاند.
راهحل: الگوهای محلی را داخل سرویس نگه دارید، مرز را صریح کنید (port، adapter، DTO سیم) و هر فراخوانی راهدور را یک Proxy بدانید که باید timeout و پاسخ تنزلیافته داشته باشد.
الگوی فریمورک در برابر الگوی اپلیکیشن (Framework vs application patterns) مهم
به زبان ساده: بعضی الگوها را فریمورک میدهد و نگه میدارد؛ بقیه را شما برای دامنهتان میسازید. نوع اول را از نقطههای توسعهاش به کار ببرید و نوع دوم را خودتان بنویسید.
بدفهمی رایج: «بهتر است Strategy را تمیز از نو پیاده کنم تا اینکه از Manager استفاده کنم.» اگر فریمورک آن شکل را میدهد، کپی کردنش کدی برای نگهداری و واژگان دومی برای آموزش به شما میدهد.
تعریف: الگوی فریمورک الگویی است که اسکلتش در فریمورک است و نقطههای تغییرش قلابهای مستند هستند (Manager::extend، Storage::extend، Notification::extend، middleware، Event::listen، http.Handler در Go). الگوی اپلیکیشن الگویی است که نیروهایش به دامنهٔ شما تعلق دارند (قواعد قیمت، واجد شرایط بودن، دستورپخت گزارش).
| پرسش | الگوی فریمورک | الگوی اپلیکیشن |
|---|---|---|
| اسکلت مال کیست؟ | فریمورک | تیم شما |
| چطور تغییرش میدهید؟ | نقطهٔ توسعهٔ مستند | کلاس یا تابع جدید |
| ریسک ارتقا | از release notes فریمورک پیروی میکند | با خودتان |
| مثال (Laravel) | Notification::extend('voice', ...) | Spec::and(Spec::segment('vip'), ...) |
| مثال (Go) | http.Handler و HandlerFunc | Rule و Group در package قیمتگذاری |
سناریوهای واقعی: ثبت یک disk سفارشی با Storage::extend، یک کانال اعلان سفارشی با Notification::extend، middleware دور mux در Go؛ در برابر یک Specification دامنهای که هیچ فریمورکی نمیدهد.
راهحل در Laravel (نقطههای توسعه):
<?php
// Three framework extension points, all the same shape: a named strategy registered at runtime.
namespace App\Providers;
use App\Notifications\VoiceChannel;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use League\Flysystem\Local\LocalFilesystemAdapter;
final class ExtendPointsServiceProvider extends ServiceProvider
{
public function boot(): void
{
// 1. Notifications: ChannelManager extends Support\Manager, so extend() adds a channel (strategy by name).
Notification::extend('voice', fn (Application $app) => new VoiceChannel());
// 2. Filesystem: FilesystemManager builds a Flysystem adapter per disk; a custom driver returns a FilesystemAdapter.
Storage::extend('audited-local', function (Application $app, array $config) {
$adapter = new LocalFilesystemAdapter($config['root']);
return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config);
});
}
}<?php
// Reading Illuminate\Pipeline\Pipeline (src/Illuminate/Pipeline/Pipeline.php): then() reduces the pipes
// with array_reduce into nested closures, so each pipe is a Decorator of the next one.
// Re-implemented here in ten lines to show that the pattern is small.
namespace App\Internals;
use Closure;
final class MiniPipeline
{
/** @param list<callable(mixed, Closure): mixed> $pipes */
public static function run(mixed $passable, array $pipes, Closure $destination): mixed
{
$stack = array_reduce(
array_reverse($pipes),
fn (Closure $next, callable $pipe) => fn ($p) => $pipe($p, $next),
$destination,
);
return $stack($passable);
}
}
// MiniPipeline::run($order, [$validate, $price, $reserve], fn ($o) => $o);مستندسازی استفاده از الگو: ADR و نامگذاری (Documenting) مهم
به زبان ساده: یک سند کوتاه بنویسید که چرا این الگو را انتخاب کردید و کلاسها را بر پایهٔ نقش دامنه نام بگذارید تا کد خودش را توضیح بدهد.
بدفهمی رایج: «اسم الگو در نام کلاس طراحی را مستند میکند.» DiscountStrategyFactoryImpl میگوید چطور ساخته شده، نه برای چه است. DiscountRules میگوید برای چه است.
تعریف: ADR (Architecture Decision Record) سندی کوتاه با عنوان، زمینه، تصمیم، وضعیت و پیامدهاست (Nygard). قواعد نامگذاری: نقش بر الگو مقدم است (Pricer، نه PricingStrategyManager)؛ کلمهٔ الگو فقط وقتی که نقش همان الگو باشد (Registry، Specification)؛ یک واژه برای یک مفهوم در کد، تست، تیکت و مستندات.
ADR-0007: Pricing rules are Strategy + Composite, built by a registry Factory
1 Status: Accepted (2026-11-25)
2 Context: Marketing adds rule kinds monthly; rules combine (stack, best-of, first).
3 A switch in checkout was edited by two teams and broke VIP prices twice.
4 Decision: Rule interface (Strategy); Group (Composite); Factory.Register(kind, ctor);
5 eligibility as Specification; money as int64 minor units.
6 Consequences (all):
7 + new kind = one type + one Register call; no edit to Engine or Factory
8 + rules are pure: tested without database or clock
9 - 4 concepts to learn; rule trees need a viewer for support staff
10 - registry is global to the Factory instance; kinds must be unique
11 Revisit when: rules need cross-cart state (loyalty points) or run in another service.| عادت نامگذاری | خوب | بو |
|---|---|---|
| اسم نقش | Pricer، Quote، Rule | PricingStrategyManagerImpl |
| کلمهٔ الگو فقط برای خود الگو | Registry، Specification | OrderHelper، CartUtil |
| یک واژه در همهجا | «rule» در کد، تیکت، رابط مدیریت | «rule»، «promotion»، «offer» برای یک چیز |
| فعل برای دستورها | PlaceOrder | OrderProcessor |
سناریوهای واقعی: docs/adr/0007-pricing-rules.md در مخزن؛ قالب pull request با یک خط «انتخاب الگو»؛ یک comment تکخطی در نقطهٔ تغییر.
راهحل: ADRها را کوتاه نگه دارید (یک یا دو صفحه، بهگفتهٔ Nygard)، شماره بزنید، هرگز تصمیم یک ADR پذیرفتهشده را ویرایش نکنید (آن را Supersede کنید) و ADR را در نقطهٔ seam از کد لینک بدهید.
راهبردهای تست برای کدِ الگودار (Testing strategies) مهم
به زبان ساده: الگوها تا حدی برای تستپذیری هستند. هر نقش را جدا تست کنید، سیمکشی را یک بار و قرارداد (Contract) را در هر مرزی که قابلتعویض است.
بدفهمی رایج: «باید هر interface را mock کنم.» اشیای کوچک واقعی (یک Strategy خالص، یک Specification) را به mock ترجیح بدهید؛ فقط چیزهای کند یا غیرقطعی را mock کنید.
تعریف: هفت لایهٔ تست برای کدِ الگودار.
| لایه | چه چیزی را تست میکند | سبک | مثال در این فصل |
|---|---|---|---|
| تست واحد نقش | یک Strategy یا Specification | تست جدولی، بدون mock | TestSpecifications، TestBuyXGetY |
| تست Composite | حالتهای Group و تودرتویی | تست جدولی با فرزندان واقعی | TestGroupModes |
| تست Factory | تعریفهای معتبر و نامعتبر | حالتهای خطا درجهیکاند | TestFactoryRejectsBadDefinitions |
| تست سیمکشی | درخت سرهمشده خروجی مورد انتظار میدهد | یک JSON طلایی | TestFactoryBuildsTreeAndEngineQuotes |
| تست قرارداد | دو adapter با هم موافقاند | همان cart، هر دو adapter | TestParity در migrate |
| تست ترتیب زنجیره | ترتیب و short-circuit یک زنجیره | handlerهای ساختگی | TestChainOrderAndShortCircuit |
| تست معماری | وابستگیها در جهت مجاز میروند | بررسی ایستا در CI | packageهای internal/، قواعد import |
Step Test run Result
1 1 go test ./pricing rules pure, tree built from JSON
2 2 add time.Now() inside a rule TestRulesArePure may pass, but the quote changes per run
3 3 move the clock into Cart.Now deterministic again
4 4 go test ./migrate TestParity: local and remote quotes equal
5 5 stop the pricing server TestFallbackWhenServiceIsDown: no-discount quoteسناریوهای واقعی: تست تخفیفِ ناپایدار بهخاطر now() داخل یک قاعده؛ کلاینت راهدوری که بیصدا از کلاینت درونپردازه فاصله گرفت تا وقتی تست قرارداد اضافه شد.
راهحل در Laravel: برای listenerها از Event::fake()، برای adapter راهدور از Http::fake() و برای قواعد از PHPUnit ساده استفاده کنید (تست مطالعهٔ موردی را ببینید).
مهاجرت یک feature به میکروسرویس: کدام الگوها زنده میمانند (Migrating a feature) حیاتی
به زبان ساده: الگوهای داخل feature با آن میروند؛ الگوهای بین feature و بقیه به قرارداد شبکه تبدیل میشوند.
بدفهمی رایج: «استخراج یعنی کپی پوشه.» فراخوانیهای درونپردازه راهدور میشوند و هرکدام timeout، fallback، schema و تست قرارداد میخواهد.
تعریف: استخراج در گامهای کوچک، به ترتیبی که ایدهٔ strangler-fig از Fowler پیشنهاد میکند: یک port جلو بگذار، adapter دوم بساز، بخشی از ترافیک را مسیریابی کن، بعد قدیمی را بازنشسته کن.
Step Action Pattern
1 1 Define Pricer port; checkout depends only on it Facade / DIP
2 2 Local adapter calls Engine in-process Adapter
3 3 Wire DTOs for request and quote ACL
4 4 Service exposes POST /quote using the same Engine Facade
5 5 Remote adapter with timeout and fallback Proxy
6 6 Contract test: Local and Remote agree Contract test
7 7 Route 5% of checkouts to Remote Strangler / feature flag
8 8 Remove Local from checkout, keep it as fallback Degraded mode| الگو | چطور زنده میماند | نکته |
|---|---|---|
| Strategy، Composite، Specification، Factory | بدون تغییر، داخل سرویس | هرگز از مرز رد نشدند |
| Facade | API عمومی میشود | نسخهبندی کنید |
| Adapter | ACL میشود | ترجمه کنید، نوعهای دامنه را نشت ندهید |
| Proxy | به شکل کلاینت راهدور ظاهر میشود | timeout، retry، fallback |
| Observer | رویداد دامنه بهعلاوهٔ outbox میشود | حداقل-یکبار، consumerهای idempotent |
| Command | پیام با کلید idempotency میشود | امن برای retry |
| Mediator | هماهنگسازی saga میشود | جبران بهجای rollback |
| Singleton | میمیرد | state سراسری پردازه بین replicaها وجود ندارد |
| Memento | state ماندگار میشود | snapshotها به پایگاهداده میروند |
راهحل در Go و Laravel:
// Package migrate shows a pricing feature leaving the monolith: one port, two adapters, one wire contract.
package migrate
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"academy/patterns-in-practice/pricing"
)
// Pricer is the port the checkout code depends on. It is the same in the monolith and after extraction.
type Pricer interface {
Quote(ctx context.Context, c pricing.Cart) (pricing.Quote, error)
}
// Local is the in-process adapter used inside the monolith.
type Local struct{ Engine pricing.Engine }
// Quote prices in the same process.
func (l Local) Quote(_ context.Context, c pricing.Cart) (pricing.Quote, error) {
return l.Engine.Price(c), nil
}
// --- wire contract (the Anti-Corruption Layer keeps domain types off the network) ---
type wireLine struct {
SKU string `json:"sku"`
Category string `json:"category"`
Qty int `json:"qty"`
Unit int64 `json:"unit_minor"`
}
type wireRequest struct {
Lines []wireLine `json:"lines"`
Segment string `json:"segment"`
Coupon string `json:"coupon,omitempty"`
NowUnix int64 `json:"now_unix"`
}
type wireQuote struct {
Subtotal int64 `json:"subtotal_minor"`
Discount int64 `json:"discount_minor"`
Total int64 `json:"total_minor"`
}
func toWire(c pricing.Cart) wireRequest {
w := wireRequest{Segment: c.Segment, Coupon: c.Coupon, NowUnix: c.Now.Unix()}
for _, l := range c.Lines {
w.Lines = append(w.Lines, wireLine{l.SKU, l.Category, l.Qty, int64(l.Unit)})
}
return w
}
func fromWire(w wireRequest) pricing.Cart {
c := pricing.Cart{Segment: w.Segment, Coupon: w.Coupon, Now: time.Unix(w.NowUnix, 0).UTC()}
for _, l := range w.Lines {
c.Lines = append(c.Lines, pricing.Line{SKU: l.SKU, Category: l.Category, Qty: l.Qty, Unit: pricing.Money(l.Unit)})
}
return c
}
// Handler is the service side: it exposes the engine over HTTP.
func Handler(e pricing.Engine) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req wireRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
q := e.Price(fromWire(req))
_ = json.NewEncoder(w).Encode(wireQuote{int64(q.Subtotal), int64(q.Discount), int64(q.Total)})
})
}
// Remote is the Proxy adapter: same port, but the call crosses the network, so it needs a timeout and a fallback.
type Remote struct {
BaseURL string
Client *http.Client
Fallback Pricer // optional degraded behaviour, e.g. "no discount"
}
// Quote calls the pricing service; on failure it uses the fallback if one is set.
func (r Remote) Quote(ctx context.Context, c pricing.Cart) (pricing.Quote, error) {
q, err := r.call(ctx, c)
if err != nil && r.Fallback != nil {
return r.Fallback.Quote(ctx, c)
}
return q, err
}
func (r Remote) call(ctx context.Context, c pricing.Cart) (pricing.Quote, error) {
body, err := json.Marshal(toWire(c))
if err != nil {
return pricing.Quote{}, err
}
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.BaseURL+"/quote", bytes.NewReader(body))
if err != nil {
return pricing.Quote{}, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := r.Client.Do(req)
if err != nil {
return pricing.Quote{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return pricing.Quote{}, fmt.Errorf("pricing service: status %d", resp.StatusCode)
}
var w wireQuote
if err := json.NewDecoder(resp.Body).Decode(&w); err != nil {
return pricing.Quote{}, err
}
return pricing.Quote{Subtotal: pricing.Money(w.Subtotal), Discount: pricing.Money(w.Discount), Total: pricing.Money(w.Total)}, nil
}package migrate
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"academy/patterns-in-practice/pricing"
)
func engine() pricing.Engine {
return pricing.Engine{Root: pricing.Group{ID: "root", Mode: pricing.Stack, Children: []pricing.Rule{
pricing.PercentOff{ID: "vip", When: pricing.InSegment("vip"), Percent: 15},
pricing.FixedOff{ID: "welcome", When: pricing.MinSubtotal(5000), Amount: 700},
}}}
}
var sample = pricing.Cart{
Segment: "vip",
Now: time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC),
Lines: []pricing.Line{{SKU: "novel", Category: "books", Qty: 2, Unit: 4000}},
}
// TestParity is the contract test: the in-process and the remote adapter must agree.
func TestParity(t *testing.T) {
srv := httptest.NewServer(Handler(engine()))
defer srv.Close()
local := Local{Engine: engine()}
remote := Remote{BaseURL: srv.URL, Client: srv.Client()}
a, _ := local.Quote(context.Background(), sample)
b, err := remote.Quote(context.Background(), sample)
if err != nil {
t.Fatal(err)
}
if a.Subtotal != b.Subtotal || a.Discount != b.Discount || a.Total != b.Total {
t.Fatalf("adapters disagree: local %+v remote %+v", a, b)
}
}
func TestFallbackWhenServiceIsDown(t *testing.T) {
down := httptest.NewServer(http.NotFoundHandler())
url := down.URL
down.Close()
noDiscount := Local{Engine: pricing.Engine{}}
r := Remote{BaseURL: url, Client: &http.Client{}, Fallback: noDiscount}
q, err := r.Quote(context.Background(), sample)
if err != nil || q.Total != q.Subtotal {
t.Fatalf("want undiscounted fallback, got %+v err=%v", q, err)
}
}<?php
// The same port in the monolith and after extraction. Checkout code depends on Pricer only.
namespace App\Pricing;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
interface Pricer
{
public function quote(Cart $cart): Quote;
}
// In-process adapter: used inside the monolith.
final readonly class LocalPricer implements Pricer
{
public function __construct(private PricingEngine $engine) {}
public function quote(Cart $cart): Quote { return $this->engine->price($cart); }
}
// Proxy adapter: same port, but the call crosses the network, so it needs a timeout, a retry and a fallback.
final readonly class RemotePricer implements Pricer
{
public function __construct(private string $baseUrl, private Pricer $fallback) {}
public function quote(Cart $cart): Quote
{
try {
$r = Http::baseUrl($this->baseUrl)
->timeout(1)->retry(2, 100, throw: false)
->post('/quote', $this->toWire($cart)) // wire DTO = the Anti-Corruption Layer
->throw()->json();
} catch (ConnectionException|\Illuminate\Http\Client\RequestException $e) {
Log::warning('pricing service unavailable, using fallback', ['error' => $e->getMessage()]);
return $this->fallback->quote($cart);
}
return new Quote($r['subtotal_minor'], [], $r['discount_minor'], $r['total_minor']);
}
private function toWire(Cart $c): array
{
return [
'segment' => $c->segment,
'coupon' => $c->coupon,
'now_unix' => $c->now->getTimestamp(),
'lines' => array_map(fn (Line $l) => [
'sku' => $l->sku, 'category' => $l->category, 'qty' => $l->qty, 'unit_minor' => $l->unit,
], $c->lines),
];
}
}
// app/Providers/AppServiceProvider.php::register() — the switch is one line of configuration:
// $this->app->bind(Pricer::class, fn ($app) => config('pricing.remote_url')
// ? new RemotePricer(config('pricing.remote_url'), new LocalPricer($app->make(PricingEngine::class)))
// : new LocalPricer($app->make(PricingEngine::class)));سازوکار
برگهٔ انتخاب (The selection worksheet) حیاتی
یک صفحه برای هر تصمیم. آن را در ADR کپی کنید.
| فیلد | پر کنید |
|---|---|
| مسئله (یک جمله، بدون نام الگو) | |
| نیروها (چه چیزی تغییر میکند، چه کسی، هر چند وقت، چه چیزی نباید) | |
| گزینهٔ کد ساده و هزینهاش | |
| نامزد A، B (و C) | |
| پیامد هرکدام: کلاس، indirection، تست، واژگان | |
| تغییر بعدیِ قابلنامبردن | |
| انتخاب و دلیل اینکه سادهترین است | |
| محرک بازبینی (چه رویدادی دوباره بازش میکند) |
اندازهگیری چگالی الگو (Measuring pattern density) مهم
سه عدد ارزان از shell. جاهایی را نشان میدهند که باید نگاه کرد؛ چیزی را ثابت نمیکنند.
# 1. Interfaces with a single implementation (Go): count interface types, then count implementers by hand.
grep -rn "type .* interface" --include=*.go . | wc -l
# 2. Pattern words in type names, the "decoration" signal.
grep -rEn "type [A-Za-z]*(Manager|Factory|Helper|Impl|Strategy|Handler)\b" --include=*.go . | wc -l
# 3. Files that change together (change coupling) over the last 6 months.
git log --since="6 months ago" --name-only --pretty=format: | sort | uniq -c | sort -rn | head -20| عدد | خوانش | اقدام |
|---|---|---|
| interface زیاد، پیادهساز کم | Speculative generality | آنهایی را که یک پیادهساز دارند و seam تست ندارند inline کنید |
| کلمهٔ الگوی زیاد در هر package | نامگذاری تزیینی | بر پایهٔ نقش تغییر نام بدهید |
| دو فایل که همیشه با هم و از دو سوی یک interface عوض میشوند | interface چیزی را پنهان نمیکند | ادغام کنید، یا نقطهٔ تغییر را جابهجا کنید |
حلقهٔ refactoring (The refactoring loop) تکمیلی
قرمز، سبز، refactor. در گام refactor سه پرسش بپرسید: کدام بو حاضر است، کدام حرکت جوابش است، و مقصد یک الگوست یا فقط کد سادهتر؟ اغلب دومی است.
Specification به شکل SQL: وقتی قاعده باید در پایگاهداده اجرا شود (Specification as SQL) مهم
یک Specification درونحافظه و یک query در SQL دو پیادهسازی از یک پرسشاند. وقتی مجموعهٔ نامزدها بزرگ است، specification را به یک بند WHERE ترجمه کنید (scope در Eloquent برای Laravel، یک تابع query برای Go) و نسخهٔ درونحافظه را برای تست و ارزیابی یک cart نگه دارید. قواعد ذخیرهشدهٔ مطالعهٔ موردی در جدولی با دقیقاً یک نسخهٔ فعال هستند:
CREATE TABLE discount_rule_sets (
id bigserial PRIMARY KEY,
version integer NOT NULL,
definition jsonb NOT NULL, -- the Def tree: kind, id, params, children
active boolean NOT NULL DEFAULT false,
created_by text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (version)
);
-- At most one active rule set. A partial unique index on a constant enforces it.
CREATE UNIQUE INDEX discount_rule_sets_one_active
ON discount_rule_sets ((true)) WHERE active;
-- Activate version 12 atomically: deactivate the old one and activate the new one in one transaction.
BEGIN;
UPDATE discount_rule_sets SET active = false WHERE active;
UPDATE discount_rule_sets SET active = true WHERE version = 12;
COMMIT;Go
Before
یک تابع با یک switch. هر نوع مشتری تازه آن را ویرایش میکند و نوع ناشناخته بیصدا تخفیف صفر میگیرد.
// Package before is the starting point: one function, one growing switch.
package before
// Discount returns the discount in cents. Every new customer type edits this function.
func Discount(kind string, subtotal int64, years int) int64 {
switch kind {
case "regular":
return 0
case "vip":
return subtotal * 15 / 100
case "loyal":
pct := int64(years)
if pct > 10 {
pct = 10
}
return subtotal * pct / 100
case "staff":
return subtotal * 30 / 100
default:
return 0
}
}After
یک نوع func بهعنوان Strategy، یک map بهعنوان registry، یک تابع سازنده که نوع ناشناخته را رد میکند. برای هر حالت interface جدید لازم نیست، چون Go اجازه میدهد یک func interface یکمتدی را برآورده کند.
// Package after applies Replace Conditional Logic with Strategy, step by step.
package after
import "fmt"
// Customer carries the inputs the strategies need.
type Customer struct {
Kind string
Years int
}
// Discounter is the Strategy interface (the point of variation).
type Discounter interface {
Discount(c Customer, subtotal int64) int64
}
// DiscounterFunc adapts a function to Discounter.
type DiscounterFunc func(Customer, int64) int64
// Discount calls the function.
func (f DiscounterFunc) Discount(c Customer, s int64) int64 { return f(c, s) }
func percent(p int64) Discounter {
return DiscounterFunc(func(_ Customer, s int64) int64 { return s * p / 100 })
}
var strategies = map[string]Discounter{
"regular": percent(0),
"vip": percent(15),
"staff": percent(30),
"loyal": DiscounterFunc(func(c Customer, s int64) int64 {
return s * int64(min(c.Years, 10)) / 100
}),
}
// For is the creation point (Introduce Polymorphic Creation). An unknown kind is an error, not a silent zero.
func For(kind string) (Discounter, error) {
d, ok := strategies[kind]
if !ok {
return nil, fmt.Errorf("unknown customer kind %q", kind)
}
return d, nil
}نگاه Go
Go چند الگو را آنقدر کوچک میکند که دیده نمیشوند:
| الگو | اصطلاح Go | چرا در Go کوچک است |
|---|---|---|
| Strategy | یک نوع func یا interface یکمتدی | هر تابع با یک نوع func میتواند interface را برآورده کند |
| Adapter | HandlerFunc | متد روی نوع func |
| Decorator | func(Handler) Handler | تابعهای درجهیک، interfaceهای ضمنی |
| Observer | slice از funcها، یا channel | فریمورک لازم نیست |
| Singleton | متغیر سطح package (کم استفاده کنید) | معمولاً یک مقدار تزریقشده |
| Factory | تابع سازندهٔ NewX، یا map از سازندهها | کلاس نیست |
| Builder | گزینههای تابعی یا struct روان | پارامتر اختیاری حالت رایج است |
| Visitor | type switch | مجموعهٔ بستهٔ نوعها به switch میخورد |
کتابخانهٔ استاندارد همین سبک را یاد میدهد: http.Handler یک متد دارد؛ sort.Interface سه تا؛ io.Reader یکی. interfaceهای کوچکِ تعریفشده در جایی که استفاده میشوند الگوها را سبک نگه میدارند (به ISP نگاه کنید). مطالعهٔ موردی کامل پایین یک package Go با شش فایل کوچک و بدون فریمورک است.
Laravel
Before
یک match روی رشته داخل یک service. همان شکل «before» در Go.
<?php
// app/Services/CustomerDiscount.php — starting point: one growing match.
namespace App\Services;
final class CustomerDiscount
{
public function for(string $kind, int $subtotal, int $years): int
{
return match ($kind) {
'regular' => 0,
'vip' => intdiv($subtotal * 15, 100),
'loyal' => intdiv($subtotal * min($years, 10), 100),
'staff' => intdiv($subtotal * 30, 100),
default => 0, // a typo in $kind silently gives no discount
};
}
}After
strategyهای برچسبخورده در container و یک کلاس factory. افزودن یک نوع مشتری یعنی یک کلاس جدید و یک اسم در فهرست service provider.
<?php
// Replace Conditional Logic with Strategy: one class per variant, one place that creates them.
namespace App\Discounts;
use Illuminate\Container\Attributes\Tag;
use InvalidArgumentException;
interface Discounter
{
public function kind(): string;
public function discount(int $subtotal, int $years): int;
}
final class Vip implements Discounter
{
public function kind(): string { return 'vip'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * 15, 100); }
}
final class Loyal implements Discounter
{
public function kind(): string { return 'loyal'; }
public function discount(int $subtotal, int $years): int { return intdiv($subtotal * min($years, 10), 100); }
}
// Creation point: the container injects every class tagged 'discounters' (see the service provider below).
final class DiscounterFactory
{
/** @var array<string, Discounter> */
private array $byKind = [];
/** @param iterable<Discounter> $discounters */
public function __construct(#[Tag('discounters')] iterable $discounters)
{
foreach ($discounters as $d) {
$this->byKind[$d->kind()] = $d;
}
}
public function for(string $kind): Discounter
{
return $this->byKind[$kind] ?? throw new InvalidArgumentException("unknown customer kind [$kind]");
}
}
// app/Providers/AppServiceProvider.php::register()
// $this->app->tag([Vip::class, Loyal::class], 'discounters');
// A new customer kind is a new class plus one name in that list; DiscounterFactory never changes.نگاه Laravel
Laravel بیشتر فهرست الگوها را به شکل نقطهٔ توسعه میدهد، پس پرسش اول این است: «آیا فریمورک از قبل دارد؟»
| نیاز | پاسخ فریمورک | الگوی زیربنایی |
|---|---|---|
| انتخاب پیادهسازی بر پایهٔ نام | زیرکلاس Manager، driver()، extend() | Factory + Strategy |
| پیچیدن رفتار دور یک درخواست | middleware در HTTP، Pipeline | Decorator + Chain |
| واکنش به یک واقعیت | Event::listen، observerهای مدل | Observer + Mediator |
| چند کانال | کانالهای Notification، Notification::extend | Strategy برای هر کانال |
| تعویض storage | diskهای Storage، Storage::extend | Adapter روی Flysystem |
| ساخت query | Query builder، scopeها | Builder + Composite (whereهای تودرتو) |
| حل وابستگیها | Container، contextual binding، tagها | Factory + Registry |
| گروه کردن پیادهسازیهای مشابه | $this->app->tag([...], 'name')، #[Tag('name')] | Registry |
مطالعهٔ موردی پایین container را فقط برای سیمکشی به کار میبرد؛ خود قواعد PHP سادهاند و برای تست فریمورک نمیخواهند.
مطالعهٔ موردی: موتور قیمتگذاری و تخفیف
نیازمندیها
- بازاریابی قواعد (درصد تخفیف، مبلغ ثابت، بخر X بگیر Y) را تعریف میکند و هفتگی بدون deploy تغییرشان میدهد.
- قواعد شرط دارند: بخش مشتری (Segment)، حداقل جمع، بازهٔ تاریخ، دسته، کوپن.
- قواعد ترکیب میشوند: بعضی جمع میشوند (Stack)، بعضی «بهترین» (Best)، بعضی «اولین که اعمال شود» (First)، و گروهها تودرتو میشوند.
- قیمت باید دقیق (پول به واحد کوچک)، تکرارپذیر (همان cart، همان قیمت) و توضیحپذیر (هر تخفیف دلیل دارد) باشد.
- یک سقف سیاستی کل تخفیف را محدود میکند؛ مجموع هرگز زیر صفر نمیرود.
- پشتیبانی باید ببیند کدام قاعده کدام تخفیف را داده.
نیروها
| نیرو | الگویی که نشانش میدهد |
|---|---|
| هر ماه نوع قاعدهٔ تازه میآید، فعلاً از یک تیم | Strategy با registry Factory |
| قواعد در درخت با سه حالت ترکیب میشوند | Composite |
| شرطها آزادانه ترکیب میشوند (and، or، not) و دوباره استفاده میشوند | Specification |
| تعریف قواعد دادهی ذخیرهشده است | Factory که از Def میسازد |
| قیمت باید تکرارپذیر و تستپذیر باشد | قواعد خالص، ساعت داخل cart |
| قیمتگذاری ممکن است بعداً سرویس جدا شود | port با adapter درونپردازه |
نامزدها و پیامدها
| نامزد | هزینه | حکم |
|---|---|---|
یک تابع با switch روی نوع قاعده | ارزان؛ هر نوع تازه یک فایل داغ را ویرایش میکند؛ تودرتویی ندارد | رد شد: نوع قاعده ماهانه عوض و تودرتو میشود |
| فقط Strategy (فهرست تخت قواعد) | یک نوع برای هر قاعده | کافی نیست: گروه و حالت ترکیب ندارد |
| Strategy + Composite | درخت، حالتها | هستهٔ انتخابشده |
| افزودن Specification برای شرطها | یک interface کوچک بهعلاوهٔ ترکیبگرها | انتخاب شد: شرطها بین نوعها تکرار میشوند |
| registry Factory از JSON | یک map، یک Build | انتخاب شد: بازاریابی داده را ویرایش میکند |
| قواعد بهصورت زبان اسکریپت (Interpreter) | parser، sandbox، بازبینی امنیتی | فعلاً رد شد (دفتر تصمیم D6) |
| قیمت بهصورت event-sourced | سنگین | رد شد: قیمت تابع خالص است، نه تاریخچه |
شکل همان طراحی است. Engine فقط به Rule وابسته است. قواعد برگ یک Spec در When دارند. Group یک Rule است که قواعد را نگه میدارد (Composite). Factory یک درخت Def ذخیرهشده را به درخت Rule تبدیل میکند.
دفتر تصمیم (Decision log)
| شناسه | تصمیم | جایگزینها | دلیل | محرک بازبینی |
|---|---|---|---|---|
| D1 | پول int64 به واحد کوچک است | float64، کتابخانهٔ decimal | دقت؛ بدون شگفتی گرد کردن | چندارزی با زیرواحد |
| D2 | Rule یک interface دومتدی (Name، Apply) و خالص است | قواعد با اثر جانبی | تستپذیر، تکرارپذیر | قاعدهای که داده بیرونی میخواهد (آن را در Cart پاس بدهید) |
| D3 | Group با سه حالت | کلاس جدا برای هر حالت | یک composite، switch کوچک | حالت چهارم که state میخواهد |
| D4 | شرطها مقدار Spec هستند | فیلد روی هر قاعده | استفادهٔ مجدد و ترکیب | Specification لازم در queryهای SQL |
| D5 | Factory یک registry است (Register(kind, ctor)) | switch روی نوع | نوع تازه بدون ویرایش factory | یکتایی نوعها بین افزونهها |
| D6 | زبان اسکریپت نداریم | الگوی Interpreter | sandbox برای نگهداری نیست | بازاریابی فرمول میخواهد، نه پارامتر |
| D7 | ساعت در Cart.Now است | time.Now() در قواعد | تست قطعی | هیچ |
| D8 | سقف سراسری سیاستی در Engine است، نه قاعده | سقف بهصورت قاعده | سقف باید بعد از همهٔ قواعد اعمال شود | سقف بهازای segment |
| D9 | نوع ناشناخته یا پارامتر بد هنگام بارگذاری خطا میدهد | رد کردن بیصدا | قیمت غلط بدتر از deploy نشدن است | هیچ |
| D10 | port به نام Pricer با adapterهای Local و Remote | صدا زدن مستقیم engine | استخراج بعدی یک adapter خرج دارد | سرویس استخراج شد |
پیادهسازی در Go
ماژول Go با نام academy/patterns-in-practice و package pricing. Cart و پول:
// Package pricing is the case-study discount engine: Strategy + Composite + Factory + Specification.
package pricing
import "time"
// Money is an amount in minor units (cents). Never use float64 for money.
type Money int64
// Line is one cart line.
type Line struct {
SKU string
Category string
Qty int
Unit Money
}
// Total is the undiscounted line total.
func (l Line) Total() Money { return l.Unit * Money(l.Qty) }
// Cart is the input of the engine. It carries Now so rules never call time.Now.
type Cart struct {
Lines []Line
Segment string // "new", "regular", "vip"
Coupon string
Now time.Time
}
// Subtotal sums all lines.
func (c Cart) Subtotal() Money {
var s Money
for _, l := range c.Lines {
s += l.Total()
}
return s
}
// CategoryTotal sums the lines of one category.
func (c Cart) CategoryTotal(category string) Money {
var s Money
for _, l := range c.Lines {
if l.Category == category {
s += l.Total()
}
}
return s
}Specification (ترکیبگرها خود الگو هستند):
package pricing
import "time"
// Spec is the Specification pattern: a named, combinable yes/no question about a cart.
type Spec interface {
IsSatisfiedBy(Cart) bool
}
// SpecFunc adapts a function to Spec.
type SpecFunc func(Cart) bool
// IsSatisfiedBy calls the function.
func (f SpecFunc) IsSatisfiedBy(c Cart) bool { return f(c) }
// Always matches every cart.
var Always Spec = SpecFunc(func(Cart) bool { return true })
// And requires every spec to hold.
func And(specs ...Spec) Spec {
return SpecFunc(func(c Cart) bool {
for _, s := range specs {
if !s.IsSatisfiedBy(c) {
return false
}
}
return true
})
}
// Or requires at least one spec to hold.
func Or(specs ...Spec) Spec {
return SpecFunc(func(c Cart) bool {
for _, s := range specs {
if s.IsSatisfiedBy(c) {
return true
}
}
return false
})
}
// Not negates a spec.
func Not(s Spec) Spec { return SpecFunc(func(c Cart) bool { return !s.IsSatisfiedBy(c) }) }
// MinSubtotal holds when the cart subtotal reaches min.
func MinSubtotal(min Money) Spec {
return SpecFunc(func(c Cart) bool { return c.Subtotal() >= min })
}
// InSegment holds for one customer segment.
func InSegment(segment string) Spec {
return SpecFunc(func(c Cart) bool { return c.Segment == segment })
}
// HasCategory holds when any line belongs to the category.
func HasCategory(category string) Spec {
return SpecFunc(func(c Cart) bool { return c.CategoryTotal(category) > 0 })
}
// Between holds inside the half-open window [from, to).
func Between(from, to time.Time) Spec {
return SpecFunc(func(c Cart) bool { return !c.Now.Before(from) && c.Now.Before(to) })
}
// WithCoupon holds when the cart carries the coupon code.
func WithCoupon(code string) Spec {
return SpecFunc(func(c Cart) bool { return c.Coupon == code })
}Strategy: قواعد.
package pricing
// Adjustment is one discount line in the quote. Amount is positive and is subtracted.
type Adjustment struct {
Rule string
Amount Money
Reason string
}
// Rule is the Strategy: one pricing algorithm behind one method.
// Apply must be pure: same cart, same adjustments, no I/O, no clock.
type Rule interface {
Name() string
Apply(Cart) []Adjustment
}
// PercentOff discounts a percentage of the subtotal (or of one category) when When holds.
type PercentOff struct {
ID string
When Spec
Percent int // 0..100
Category string // empty means the whole cart
}
// Name returns the rule id.
func (r PercentOff) Name() string { return r.ID }
// Apply computes the percentage discount with integer math (floor).
func (r PercentOff) Apply(c Cart) []Adjustment {
if !r.When.IsSatisfiedBy(c) {
return nil
}
base := c.Subtotal()
if r.Category != "" {
base = c.CategoryTotal(r.Category)
}
amount := base * Money(r.Percent) / 100
if amount <= 0 {
return nil
}
return []Adjustment{{Rule: r.ID, Amount: amount, Reason: "percent off"}}
}
// FixedOff subtracts a fixed amount, never more than the subtotal.
type FixedOff struct {
ID string
When Spec
Amount Money
}
// Name returns the rule id.
func (r FixedOff) Name() string { return r.ID }
// Apply returns one adjustment capped by the subtotal.
func (r FixedOff) Apply(c Cart) []Adjustment {
if !r.When.IsSatisfiedBy(c) {
return nil
}
amount := min(r.Amount, c.Subtotal())
if amount <= 0 {
return nil
}
return []Adjustment{{Rule: r.ID, Amount: amount, Reason: "fixed off"}}
}
// BuyXGetY gives the cheapest free unit in every complete group of Buy+Get units of one SKU.
type BuyXGetY struct {
ID string
When Spec
SKU string
Buy int
Get int
}
// Name returns the rule id.
func (r BuyXGetY) Name() string { return r.ID }
// Apply gives Get free units per Buy+Get units.
func (r BuyXGetY) Apply(c Cart) []Adjustment {
if !r.When.IsSatisfiedBy(c) || r.Buy <= 0 || r.Get <= 0 {
return nil
}
var out []Adjustment
for _, l := range c.Lines {
if l.SKU != r.SKU {
continue
}
free := l.Qty / (r.Buy + r.Get) * r.Get
if free > 0 {
out = append(out, Adjustment{Rule: r.ID, Amount: l.Unit * Money(free), Reason: "free units"})
}
}
return out
}Composite: گروه.
package pricing
// Mode says how a Group combines the adjustments of its children.
type Mode int
const (
// Stack applies every child (all discounts add up).
Stack Mode = iota
// Best applies only the child with the largest total discount.
Best
// First applies the first child that produces any discount.
First
)
// Group is the Composite: a Rule made of Rules. A Group can contain Groups.
type Group struct {
ID string
Mode Mode
Children []Rule
}
// Name returns the group id.
func (g Group) Name() string { return g.ID }
// Apply combines child results according to Mode.
func (g Group) Apply(c Cart) []Adjustment {
switch g.Mode {
case First:
for _, ch := range g.Children {
if adj := ch.Apply(c); len(adj) > 0 {
return adj
}
}
return nil
case Best:
var best []Adjustment
var bestTotal Money
for _, ch := range g.Children {
adj := ch.Apply(c)
if t := sum(adj); t > bestTotal {
best, bestTotal = adj, t
}
}
return best
default:
var all []Adjustment
for _, ch := range g.Children {
all = append(all, ch.Apply(c)...)
}
return all
}
}
func sum(adj []Adjustment) Money {
var s Money
for _, a := range adj {
s += a.Amount
}
return s
}Factory: registry و تعریف ذخیرهشده.
package pricing
import (
"encoding/json"
"fmt"
"time"
)
// Def is the stored, data-only description of a rule (a JSON row in the database).
type Def struct {
Kind string `json:"kind"`
ID string `json:"id"`
Params json.RawMessage `json:"params,omitempty"`
Segment string `json:"segment,omitempty"`
MinTotal Money `json:"min_total,omitempty"`
From *time.Time `json:"from,omitempty"`
To *time.Time `json:"to,omitempty"`
Children []Def `json:"children,omitempty"`
}
// Constructor builds one kind of rule from a Def.
type Constructor func(f *Factory, d Def) (Rule, error)
// Factory is a registry-based factory: new kinds are added with Register, never by editing a switch.
type Factory struct {
kinds map[string]Constructor
}
// NewFactory returns a factory with the built-in kinds registered.
func NewFactory() *Factory {
f := &Factory{kinds: map[string]Constructor{}}
f.Register("percent_off", percentOff)
f.Register("fixed_off", fixedOff)
f.Register("buy_x_get_y", buyXGetY)
f.Register("group", group)
return f
}
// Register adds or replaces a kind.
func (f *Factory) Register(kind string, c Constructor) { f.kinds[kind] = c }
// Build creates a rule tree from a definition tree.
func (f *Factory) Build(d Def) (Rule, error) {
c, ok := f.kinds[d.Kind]
if !ok {
return nil, fmt.Errorf("pricing: unknown rule kind %q (rule %q)", d.Kind, d.ID)
}
return c(f, d)
}
// whenOf turns the common Def fields into a Specification.
func whenOf(d Def) Spec {
specs := []Spec{}
if d.Segment != "" {
specs = append(specs, InSegment(d.Segment))
}
if d.MinTotal > 0 {
specs = append(specs, MinSubtotal(d.MinTotal))
}
if d.From != nil && d.To != nil {
specs = append(specs, Between(*d.From, *d.To))
}
if len(specs) == 0 {
return Always
}
return And(specs...)
}
func percentOff(_ *Factory, d Def) (Rule, error) {
var p struct {
Percent int `json:"percent"`
Category string `json:"category"`
}
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: rule %q: %w", d.ID, err)
}
if p.Percent <= 0 || p.Percent > 100 {
return nil, fmt.Errorf("pricing: rule %q: percent must be 1..100, got %d", d.ID, p.Percent)
}
return PercentOff{ID: d.ID, When: whenOf(d), Percent: p.Percent, Category: p.Category}, nil
}
func fixedOff(_ *Factory, d Def) (Rule, error) {
var p struct {
Amount Money `json:"amount"`
}
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: rule %q: %w", d.ID, err)
}
if p.Amount <= 0 {
return nil, fmt.Errorf("pricing: rule %q: amount must be positive", d.ID)
}
return FixedOff{ID: d.ID, When: whenOf(d), Amount: p.Amount}, nil
}
func buyXGetY(_ *Factory, d Def) (Rule, error) {
var p struct {
SKU string `json:"sku"`
Buy int `json:"buy"`
Get int `json:"get"`
}
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: rule %q: %w", d.ID, err)
}
if p.SKU == "" || p.Buy <= 0 || p.Get <= 0 {
return nil, fmt.Errorf("pricing: rule %q: sku, buy and get are required", d.ID)
}
return BuyXGetY{ID: d.ID, When: whenOf(d), SKU: p.SKU, Buy: p.Buy, Get: p.Get}, nil
}
func group(f *Factory, d Def) (Rule, error) {
var p struct {
Mode string `json:"mode"`
}
if len(d.Params) > 0 {
if err := json.Unmarshal(d.Params, &p); err != nil {
return nil, fmt.Errorf("pricing: group %q: %w", d.ID, err)
}
}
modes := map[string]Mode{"": Stack, "stack": Stack, "best": Best, "first": First}
mode, ok := modes[p.Mode]
if !ok {
return nil, fmt.Errorf("pricing: group %q: unknown mode %q", d.ID, p.Mode)
}
g := Group{ID: d.ID, Mode: mode}
for _, cd := range d.Children {
child, err := f.Build(cd)
if err != nil {
return nil, err
}
g.Children = append(g.Children, child)
}
return g, nil
}موتور و نردههای ایمنیاش:
package pricing
// Quote is the result of pricing a cart.
type Quote struct {
Subtotal Money
Adjustments []Adjustment
Discount Money
Total Money
}
// Engine runs the root rule and applies the global guard rails.
type Engine struct {
Root Rule
// MaxDiscountPercent caps the total discount (policy, not a rule). 0 means no cap.
MaxDiscountPercent int
}
// Price returns a quote. It never returns a negative total.
func (e Engine) Price(c Cart) Quote {
q := Quote{Subtotal: c.Subtotal()}
if e.Root != nil {
q.Adjustments = e.Root.Apply(c)
}
q.Discount = sum(q.Adjustments)
if e.MaxDiscountPercent > 0 {
if limit := q.Subtotal * Money(e.MaxDiscountPercent) / 100; q.Discount > limit {
q.Discount = limit
}
}
q.Discount = min(q.Discount, q.Subtotal)
q.Total = q.Subtotal - q.Discount
return q
}تستها:
package pricing
import (
"encoding/json"
"testing"
"time"
)
var now = time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC)
func cart(segment string, lines ...Line) Cart {
return Cart{Lines: lines, Segment: segment, Now: now}
}
func TestSpecifications(t *testing.T) {
c := cart("vip", Line{SKU: "tv", Category: "electronics", Qty: 1, Unit: 50000})
cases := []struct {
name string
spec Spec
want bool
}{
{"vip segment", InSegment("vip"), true},
{"min subtotal not met", MinSubtotal(60000), false},
{"and", And(InSegment("vip"), HasCategory("electronics")), true},
{"or", Or(InSegment("new"), MinSubtotal(1)), true},
{"not", Not(InSegment("vip")), false},
{"window open", Between(now.Add(-time.Hour), now.Add(time.Hour)), true},
{"window end is exclusive", Between(now.Add(-time.Hour), now), false},
}
for _, tc := range cases {
if got := tc.spec.IsSatisfiedBy(c); got != tc.want {
t.Errorf("%s: got %v, want %v", tc.name, got, tc.want)
}
}
}
func TestRulesArePure(t *testing.T) {
c := cart("regular", Line{SKU: "a", Category: "books", Qty: 3, Unit: 1000})
r := PercentOff{ID: "ten", When: Always, Percent: 10}
first, second := r.Apply(c), r.Apply(c)
if len(first) != 1 || first[0].Amount != 300 || second[0].Amount != 300 {
t.Fatalf("unexpected adjustments: %v %v", first, second)
}
}
func TestBuyXGetY(t *testing.T) {
c := cart("regular", Line{SKU: "mug", Qty: 7, Unit: 500})
adj := BuyXGetY{ID: "b2g1", When: Always, SKU: "mug", Buy: 2, Get: 1}.Apply(c)
if len(adj) != 1 || adj[0].Amount != 1000 { // 7 / 3 = 2 free units
t.Fatalf("got %v", adj)
}
}
func TestGroupModes(t *testing.T) {
c := cart("vip", Line{SKU: "a", Qty: 1, Unit: 10000})
ten := PercentOff{ID: "ten", When: Always, Percent: 10}
vip := PercentOff{ID: "vip", When: InSegment("vip"), Percent: 15}
cases := []struct {
name string
mode Mode
want Money
}{
{"stack", Stack, 2500},
{"best", Best, 1500},
{"first", First, 1000},
}
for _, tc := range cases {
g := Group{ID: tc.name, Mode: tc.mode, Children: []Rule{ten, vip}}
if got := sum(g.Apply(c)); got != tc.want {
t.Errorf("%s: got %d, want %d", tc.name, got, tc.want)
}
}
}
const rulesJSON = `{
"kind": "group", "id": "root", "params": {"mode": "stack"},
"children": [
{"kind": "percent_off", "id": "vip15", "segment": "vip", "params": {"percent": 15}},
{"kind": "group", "id": "coupons", "params": {"mode": "best"}, "children": [
{"kind": "fixed_off", "id": "welcome", "min_total": 5000, "params": {"amount": 700}},
{"kind": "percent_off", "id": "books5", "params": {"percent": 5, "category": "books"}}
]}
]
}`
func TestFactoryBuildsTreeAndEngineQuotes(t *testing.T) {
var def Def
if err := json.Unmarshal([]byte(rulesJSON), &def); err != nil {
t.Fatal(err)
}
root, err := NewFactory().Build(def)
if err != nil {
t.Fatal(err)
}
c := cart("vip", Line{SKU: "novel", Category: "books", Qty: 2, Unit: 4000})
q := Engine{Root: root}.Price(c)
// subtotal 8000; vip15 = 1200; best of welcome(700) and books5(400) = 700
if q.Subtotal != 8000 || q.Discount != 1900 || q.Total != 6100 {
t.Fatalf("unexpected quote: %+v", q)
}
}
func TestFactoryRejectsBadDefinitions(t *testing.T) {
f := NewFactory()
bad := []Def{
{Kind: "nope", ID: "x"},
{Kind: "percent_off", ID: "p", Params: json.RawMessage(`{"percent": 150}`)},
{Kind: "group", ID: "g", Params: json.RawMessage(`{"mode": "random"}`)},
}
for _, d := range bad {
if _, err := f.Build(d); err == nil {
t.Errorf("rule %q: expected an error", d.ID)
}
}
}
func TestEngineGuardRails(t *testing.T) {
c := cart("vip", Line{SKU: "a", Qty: 1, Unit: 1000})
e := Engine{
Root: Group{ID: "all", Mode: Stack, Children: []Rule{
PercentOff{ID: "a", When: Always, Percent: 80},
PercentOff{ID: "b", When: Always, Percent: 80},
}},
MaxDiscountPercent: 50,
}
if q := e.Price(c); q.Discount != 500 || q.Total != 500 {
t.Fatalf("cap not applied: %+v", q)
}
if q := (Engine{}).Price(c); q.Total != 1000 {
t.Fatalf("empty engine must not discount: %+v", q)
}
}پیادهسازی در Laravel
همان طراحی در PHP 8.4 و Laravel 13. قواعد و specificationها کلاسهای سادهاند؛ فقط service provider با فریمورک کار دارد.
<?php
// app/Pricing/Cart.php — input of the engine. Money is an integer in minor units (cents).
namespace App\Pricing;
use DateTimeImmutable;
final readonly class Line
{
public function __construct(
public string $sku,
public string $category,
public int $qty,
public int $unit,
) {}
public function total(): int
{
return $this->unit * $this->qty;
}
}
final readonly class Cart
{
/** @param list<Line> $lines */
public function __construct(
public array $lines,
public string $segment,
public DateTimeImmutable $now,
public ?string $coupon = null,
) {}
public function subtotal(): int
{
return array_sum(array_map(fn (Line $l) => $l->total(), $this->lines));
}
public function categoryTotal(string $category): int
{
return array_sum(array_map(
fn (Line $l) => $l->category === $category ? $l->total() : 0,
$this->lines,
));
}
}<?php
// app/Pricing/Specification.php — the Specification pattern: combinable yes/no questions about a cart.
namespace App\Pricing;
use Closure;
use DateTimeImmutable;
interface Specification
{
public function isSatisfiedBy(Cart $cart): bool;
}
final readonly class Spec implements Specification
{
private function __construct(private Closure $test) {}
public static function always(): self
{
return new self(fn () => true);
}
public static function segment(string $segment): self
{
return new self(fn (Cart $c) => $c->segment === $segment);
}
public static function minSubtotal(int $min): self
{
return new self(fn (Cart $c) => $c->subtotal() >= $min);
}
public static function hasCategory(string $category): self
{
return new self(fn (Cart $c) => $c->categoryTotal($category) > 0);
}
/** Half-open window [from, to). */
public static function between(DateTimeImmutable $from, DateTimeImmutable $to): self
{
return new self(fn (Cart $c) => $c->now >= $from && $c->now < $to);
}
public static function and(Specification ...$specs): self
{
return new self(fn (Cart $c) => array_all($specs, fn (Specification $s) => $s->isSatisfiedBy($c)));
}
public static function or(Specification ...$specs): self
{
return new self(fn (Cart $c) => array_any($specs, fn (Specification $s) => $s->isSatisfiedBy($c)));
}
public static function not(Specification $spec): self
{
return new self(fn (Cart $c) => ! $spec->isSatisfiedBy($c));
}
public function isSatisfiedBy(Cart $cart): bool
{
return ($this->test)($cart);
}
}<?php
// app/Pricing/Rules.php — Strategy (PricingRule) and Composite (RuleGroup).
namespace App\Pricing;
final readonly class Adjustment
{
public function __construct(public string $rule, public int $amount, public string $reason) {}
}
/** The Strategy. apply() must be pure: no I/O, no now(), no randomness. */
interface PricingRule
{
public function name(): string;
/** @return list<Adjustment> */
public function apply(Cart $cart): array;
}
final readonly class PercentOff implements PricingRule
{
public function __construct(
private string $id,
private Specification $when,
private int $percent,
private string $category = '',
) {}
public function name(): string
{
return $this->id;
}
public function apply(Cart $cart): array
{
if (! $this->when->isSatisfiedBy($cart)) {
return [];
}
$base = $this->category === '' ? $cart->subtotal() : $cart->categoryTotal($this->category);
$amount = intdiv($base * $this->percent, 100);
return $amount > 0 ? [new Adjustment($this->id, $amount, 'percent off')] : [];
}
}
final readonly class FixedOff implements PricingRule
{
public function __construct(private string $id, private Specification $when, private int $amount) {}
public function name(): string
{
return $this->id;
}
public function apply(Cart $cart): array
{
if (! $this->when->isSatisfiedBy($cart)) {
return [];
}
$amount = min($this->amount, $cart->subtotal());
return $amount > 0 ? [new Adjustment($this->id, $amount, 'fixed off')] : [];
}
}
enum Mode: string
{
case Stack = 'stack'; // every child applies
case Best = 'best'; // only the largest discount applies
case First = 'first'; // the first child that discounts wins
}
/** The Composite: a rule made of rules. A group may contain groups. */
final readonly class RuleGroup implements PricingRule
{
/** @param list<PricingRule> $children */
public function __construct(private string $id, private Mode $mode, private array $children) {}
public function name(): string
{
return $this->id;
}
public function apply(Cart $cart): array
{
return match ($this->mode) {
Mode::Stack => array_merge(...array_map(fn (PricingRule $r) => $r->apply($cart), $this->children)) ?: [],
Mode::First => $this->first($cart),
Mode::Best => $this->best($cart),
};
}
private function first(Cart $cart): array
{
foreach ($this->children as $child) {
if ($adjustments = $child->apply($cart)) {
return $adjustments;
}
}
return [];
}
private function best(Cart $cart): array
{
$best = [];
$bestTotal = 0;
foreach ($this->children as $child) {
$adjustments = $child->apply($cart);
$total = array_sum(array_map(fn (Adjustment $a) => $a->amount, $adjustments));
if ($total > $bestTotal) {
[$best, $bestTotal] = [$adjustments, $total];
}
}
return $best;
}
}<?php
// app/Pricing/RuleFactory.php — registry-based Factory: kinds are added with register(), never by editing a match.
namespace App\Pricing;
use DateTimeImmutable;
use InvalidArgumentException;
final class RuleFactory
{
/** @var array<string, callable(array, self): PricingRule> */
private array $kinds = [];
public function __construct()
{
$this->register('percent_off', fn (array $d) => new PercentOff(
$d['id'], self::when($d), $this->percent($d), $d['params']['category'] ?? '',
));
$this->register('fixed_off', fn (array $d) => new FixedOff(
$d['id'], self::when($d), $this->positive($d, 'amount'),
));
$this->register('group', function (array $d, self $f) {
$mode = Mode::tryFrom($d['params']['mode'] ?? 'stack')
?? throw new InvalidArgumentException("group {$d['id']}: unknown mode");
return new RuleGroup($d['id'], $mode, array_map($f->build(...), $d['children'] ?? []));
});
}
public function register(string $kind, callable $constructor): void
{
$this->kinds[$kind] = $constructor;
}
/** @param array<string, mixed> $definition decoded JSON from the discount_rules table */
public function build(array $definition): PricingRule
{
$make = $this->kinds[$definition['kind'] ?? ''] ?? throw new InvalidArgumentException(
sprintf('unknown rule kind "%s" (rule "%s")', $definition['kind'] ?? '', $definition['id'] ?? '?'),
);
return $make($definition, $this);
}
private static function when(array $d): Specification
{
$specs = [];
if (! empty($d['segment'])) {
$specs[] = Spec::segment($d['segment']);
}
if (! empty($d['min_total'])) {
$specs[] = Spec::minSubtotal((int) $d['min_total']);
}
if (! empty($d['from']) && ! empty($d['to'])) {
$specs[] = Spec::between(new DateTimeImmutable($d['from']), new DateTimeImmutable($d['to']));
}
return $specs === [] ? Spec::always() : Spec::and(...$specs);
}
private function percent(array $d): int
{
$p = (int) ($d['params']['percent'] ?? 0);
return ($p >= 1 && $p <= 100) ? $p : throw new InvalidArgumentException("rule {$d['id']}: percent must be 1..100");
}
private function positive(array $d, string $key): int
{
$v = (int) ($d['params'][$key] ?? 0);
return $v > 0 ? $v : throw new InvalidArgumentException("rule {$d['id']}: $key must be positive");
}
}<?php
// app/Pricing/PricingEngine.php — runs the root rule and applies the global guard rails.
namespace App\Pricing;
final readonly class Quote
{
/** @param list<Adjustment> $adjustments */
public function __construct(
public int $subtotal,
public array $adjustments,
public int $discount,
public int $total,
) {}
}
final readonly class PricingEngine
{
public function __construct(private PricingRule $root, private int $maxDiscountPercent = 0) {}
public function price(Cart $cart): Quote
{
$subtotal = $cart->subtotal();
$adjustments = $this->root->apply($cart);
$discount = array_sum(array_map(fn (Adjustment $a) => $a->amount, $adjustments));
if ($this->maxDiscountPercent > 0) {
$discount = min($discount, intdiv($subtotal * $this->maxDiscountPercent, 100));
}
$discount = min($discount, $subtotal);
return new Quote($subtotal, $adjustments, $discount, $subtotal - $discount);
}
}<?php
// app/Providers/PricingServiceProvider.php — wiring: the only place that knows the concrete classes.
namespace App\Providers;
use App\Pricing\PricingEngine;
use App\Pricing\RuleFactory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
final class PricingServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(RuleFactory::class);
// Build the rule tree once per process from the active definition (one JSON document per version).
$this->app->singleton(PricingEngine::class, function ($app) {
$json = DB::table('discount_rule_sets')->where('active', true)->value('definition');
$root = $app->make(RuleFactory::class)->build(json_decode($json, true, flags: JSON_THROW_ON_ERROR));
return new PricingEngine($root, maxDiscountPercent: config('pricing.max_discount_percent', 50));
});
}
}<?php
// tests/Unit/PricingEngineTest.php — pure unit tests: no database, no container, no HTTP.
namespace Tests\Unit;
use App\Pricing\Cart;
use App\Pricing\Line;
use App\Pricing\PricingEngine;
use App\Pricing\RuleFactory;
use DateTimeImmutable;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
final class PricingEngineTest extends TestCase
{
private const RULES = [
'kind' => 'group', 'id' => 'root', 'params' => ['mode' => 'stack'],
'children' => [
['kind' => 'percent_off', 'id' => 'vip15', 'segment' => 'vip', 'params' => ['percent' => 15]],
['kind' => 'group', 'id' => 'coupons', 'params' => ['mode' => 'best'], 'children' => [
['kind' => 'fixed_off', 'id' => 'welcome', 'min_total' => 5000, 'params' => ['amount' => 700]],
['kind' => 'percent_off', 'id' => 'books5', 'params' => ['percent' => 5, 'category' => 'books']],
]],
],
];
private function cart(string $segment, Line ...$lines): Cart
{
return new Cart(array_values($lines), $segment, new DateTimeImmutable('2026-11-27T10:00:00Z'));
}
public function test_factory_builds_the_tree_and_the_engine_quotes(): void
{
$engine = new PricingEngine((new RuleFactory())->build(self::RULES));
$quote = $engine->price($this->cart('vip', new Line('novel', 'books', 2, 4000)));
// subtotal 8000; vip15 = 1200; best of welcome (700) and books5 (400) = 700
$this->assertSame([8000, 1900, 6100], [$quote->subtotal, $quote->discount, $quote->total]);
}
public function test_the_cap_never_lets_the_total_go_below_half(): void
{
$rules = ['kind' => 'group', 'id' => 'all', 'children' => [
['kind' => 'percent_off', 'id' => 'a', 'params' => ['percent' => 80]],
['kind' => 'percent_off', 'id' => 'b', 'params' => ['percent' => 80]],
]];
$engine = new PricingEngine((new RuleFactory())->build($rules), maxDiscountPercent: 50);
$quote = $engine->price($this->cart('regular', new Line('a', 'x', 1, 1000)));
$this->assertSame(500, $quote->total);
}
/** @return iterable<string, array{array<string, mixed>}> */
public static function badDefinitions(): iterable
{
yield 'unknown kind' => [['kind' => 'nope', 'id' => 'x']];
yield 'percent out of range' => [['kind' => 'percent_off', 'id' => 'p', 'params' => ['percent' => 150]]];
yield 'unknown group mode' => [['kind' => 'group', 'id' => 'g', 'params' => ['mode' => 'random']]];
}
#[DataProvider('badDefinitions')]
public function test_the_factory_rejects_bad_definitions(array $definition): void
{
$this->expectException(InvalidArgumentException::class);
(new RuleFactory())->build($definition);
}
}طراحی در طول زمان چطور تغییر میکند
Week Change request What changes in code
1 W1 "VIP gets 15%" PercentOff + InSegment spec; one Register
2 W3 "Welcome 7 off from 50 total" FixedOff + MinSubtotal spec; data row only
3 W6 "Black Friday, best of two coupons" Group(Best); window spec; data row only
4 W9 "Buy 2 get 1 on mugs" BuyXGetY type + one Register("buy_x_get_y")
5 W14 "Never discount more than 50%" Engine.MaxDiscountPercent (policy)
6 W20 "Loyalty points" Rules need account data: add it to Cart, not a global
7 W30 "Pricing is its own team" Port + Remote adapter; contract test (migrate)هفتههای ۱ و ۲ و ۳ داده را عوض میکنند، نه کد را: این فایدهٔ composite و registry است. هفتهٔ ۶ وسوسهٔ همیشگیِ دست بردن به یک global است؛ دفتر تصمیم میگوید آن را به cart اضافه کنید تا قواعد خالص بمانند.
حل مسئلههای کلاسیک
| مسئله | زبان الگوی ترجیحی | هزینه | حد |
|---|---|---|---|
switch در حال رشدی که چند نفر ویرایشش میکنند | map از funcها، بعد Strategy | یک map یا یک نوع برای هر حالت | برای دو حالت پایدار لازم نیست |
| شرطها به شکلهای زیاد ترکیب میشوند | Specification | یک interface و ترکیبگرها | مجموعهٔ نامزد بزرگ به SQL نیاز دارد |
| قواعد گروه میسازند | Composite | هزینهٔ ارزیابی درخت | باید جلوی چرخه را گرفت |
| رفتار باید دور فراخوانی بپیچد | زنجیرهٔ Decorator | حساسیت به ترتیب | ترتیب مستند میخواهد |
| واکنشدهندههای نامعلوم باید واکنش دهند | Observer یا رویداد | جریان کنترل پنهان | برای کار مرتب مناسب نیست |
| افزونههای شخص ثالث | Registry + extend() | قرارداد عمومی برای نگهداری | فقط وقتی شخص ثالث هست |
| زیرساخت قابلتعویض | Port + Adapter | یک adapter برای هر backend | چیزی را که هرگز عوض نمیشود نپیچید |
| Undo یا ممیزی | Command + Memento | اندازهٔ snapshot | state بزرگ diff میخواهد |
| فراخوانی راهدور ناپایدار میشود | Proxy با timeout و fallback | پاسخهای تنزلیافته | تصمیم محصولی لازم دارد |
| الگوی بیش از حد | Inline Class، Collapse Hierarchy | حذف کردن ریسکی به نظر میرسد | تستها را نگه دارید |
مسئله: switch خدا در checkout
نشانه: یک switch روی نوع پرداخت در controller، پنج case، دو تیم. حرکت: Replace Conditional Logic with Strategy، بعد Manager با extend(). تا حالت سوم switch را نگه دارید.
مسئله: سوپ الگو
نشانه: هر کلاس اسم الگو دارد و کسی نمیگوید به کدام نیرو خدمت میکند. حرکت: برای هر نوع بپرسید «کدام نیرو؟»؛ جوابی نبود، inline کنید.
مسئله: Singleton تستناپذیر
نشانه: تستها به ترتیب اجرا وابستهاند. حرکت: تزریق کنید و اگر یک نمونه لازم است container نگهش دارد.
انتخاب: کدام الگو، یا هیچکدام
| وضعیت | توصیه | تکنیک اضافه | دلیل |
|---|---|---|---|
| یک رفتار، بدون حالت معلوم | تابع ساده | یک comment که محور را نام ببرد | ارزانترین؛ منتظر نیرو بمان |
| دو حالت، یک تیم | switch یا map | تست جدولی | هنوز ساده است |
| سه حالت یا بیشتر، یک تیم | Strategy بر پایهٔ نام | تابع factory با خطا برای ناشناخته | حالتها رشد میکنند |
| حالتها را تیمهای دیگر اضافه میکنند | Registry + extend() | تست قرارداد | باز برای توسعه |
| شرطها ترکیب میشوند | Specification | And، Or، Not | استفادهٔ مجدد |
| گروههای تودرتو | Composite | حالتها، بررسی چرخه | درختها |
| پیچیدن رفتار | زنجیرهٔ Decorator | تست ترتیب | مقطعی |
| پخش واکنشها | رویدادها | اگر بینسرویسی است Outbox | جداسازی |
| مجموعهٔ عملیات روی درخت پایدار | Visitor | مجموعهٔ بستهٔ انواع گره | عملیات تازه بدون ویرایش |
| درخت ناپایدار، عملیات پایدار | متد روی گرهها | هیچ | Visitor آسیب میزند |
| شیء سختساخت | Builder | دستورپختهای Director | گامها و پیشتنظیمها |
| شیء ارزان با ساخت ساده | سازنده | هیچ | factory لازم نیست |
در معماری: از یک پردازه تا یک سیستم توزیعشده
مونولیت (Monolith): یک پردازه، یک پایگاهداده
مثال روزمره. یک فروشگاه کوچک در یک اپ Laravel. checkout از Pipeline با سه pipe (بررسی موجودی، اعمال تخفیف، رزرو) و یک match برای دو نوع پرداخت استفاده میکند. هنوز PaymentManager نیست؛ حالت دوم فقط یک شاخهٔ match است. ADR میگوید «در دروازهٔ سوم بازبینی شود».
مثال تولیدی. net/http در کتابخانهٔ استاندارد Go کتابخانهای هماندازهٔ یک مونولیت است که از چند الگوی کوچک ساخته شده: Handler (Strategy)، HandlerFunc (Adapter)، StripPrefix و TimeoutHandler (Decoratorها)، ServeMux (Registry). Manager خود Laravel را cache، mail، notifications و filesystem دوباره استفاده میکنند.
قاعدهٔ سرانگشتی: در مونولیت ارزانترین الگو آن است که با یک commit حذفش کنید.
مونولیت ماژولار و چند پایگاهداده
ماژولها دادهشان را دارند و از طریق portها حرف میزنند. Pricing Pricer را عرضه میکند؛ checkout فقط به port وابسته است؛ هیچکس دیگر نوعهای قاعده را import نمیکند (در Go زیر internal/ بگذارید؛ در PHP با یک بررسی ایستای وابستگی در CI اعمالش کنید).
| ابزار مرز | الگو | چه چیزی را محافظت میکند |
|---|---|---|
| Port (interface متعلق به مصرفکننده) | DIP، Facade | مصرفکنندهها را از درون قواعد |
| رویدادهای ماژول | Observer | ماژولها را از ترتیب کار یکدیگر |
| مدل خواندن برای هر ماژول | CQRS-lite | گزارشها را از جدولهای ماژولهای دیگر |
| DTO سیم حتی درونپردازه | ACL | نوعهای دامنه را از نشت |
مثال روزمره. ماژول Pricing با Pricer و adapter به نام Local؛ ماژول گزارش quotes را از view خودش میخواند. مثال تولیدی. یک مونولیت با مرزهای ماژول که در CI بررسی میشود، یک schema برای هر ماژول، و استخراج بعداً با جایگزین کردن Local با Remote (snippet مربوط به migrate).
میکروسرویس: الگوها با یک شبکه در وسط
اینکه کدام الگوها زنده میمانند همان جدول مهاجرت یک feature است. الگوهای سطح سرویس از بخش قبلی واقعی میشوند: gateway در جلو، ACL در هر یکپارچهسازی، outbox برای رویدادها، saga برای جریانهای چندسرویسی، consumerهای idempotent.
Step Flow: place an order across three services
1 1 Gateway -> Checkout: POST /orders (Idempotency-Key: k1)
2 2 Checkout -> Pricing: POST /quote (timeout 300 ms, fallback no discount)
3 3 Checkout: INSERT order + outbox row in one local transaction
4 4 Relay -> broker: OrderPlaced (at least once)
5 5 Payment consumer: dedup by event id, charge, emit PaymentCaptured
6 6 Stock consumer: reserve; on failure emit StockFailed
7 7 Checkout (saga step): on StockFailed, cancel order, emit RefundRequestedمثال روزمره. Checkout قیمت را با HTTP از pricing میگیرد و fallback دارد؛ روز بد pricing یعنی بدون تخفیف، نه بدون checkout. مثال تولیدی. همین جریان با جدول outbox:
CREATE TABLE outbox (
id bigserial PRIMARY KEY,
aggregate_id text NOT NULL,
type text NOT NULL, -- e.g. OrderPlaced
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
-- The relay reads unpublished rows in id order and marks them published after the broker acknowledges.
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;دادههای توزیعشده: replicaها، cacheها و schemaهای مشترک
الگوها اینجا با کهنگی داده روبهرو میشوند.
| جا | الگوی در خطر | شکست | محافظ |
|---|---|---|---|
| مجموعهٔ قواعدِ cacheشده در هر instance (Flyweight) | Proxy + Flyweight | instanceها هنگام rollout قیمت متفاوت میدهند | rule_set_version را در هر قیمت بگذارید؛ checkout نسخهٔ قیمت را رعایت کند |
| replica خواندنی برای قیمتها | Strategy که داده میخواند | تأخیر replica قواعد کهنه نشان میدهد | قواعد را از primary یا بر پایهٔ نسخه بخوانید |
| رویدادها (Observer) | Observer | تکرار، جابهجایی ترتیب | consumerهای idempotent، کلید ترتیب برای هر aggregate |
| Saga (Mediator) | Command + State | نیمهکاره ماندن | timeout، جبران، dead-letter queue |
| Singleton | Singleton | state هر پردازه با replica دیگر فرق دارد | storage مشترک یا هیچ |
مثال روزمره. اپ Laravel با دو سرور درخت قواعد را در singleton هر پردازه نگه میدارد؛ بعد از فعال کردن نسخهٔ ۱۲ یک سرور تا boot بعدی با نسخهٔ ۱۱ قیمت میدهد. راهحل: نسخه در قیمت و یک سیگنال refresh. مثال تولیدی. قیمتها rule_set_version دارند؛ سفارش آن را ذخیره میکند؛ پشتیبانی میتواند تخفیف دقیق را از نسخهٔ ذخیرهشده دوباره حساب کند.
مسیر مقیاس: ۱×، ۱۰×، ۱۰۰×
| بار | وضعیت الگو | تغییر |
|---|---|---|
| ۱× (یک تیم، چند قاعده) | کد ساده و map از funcها | هنوز interface نیست |
| ۱۰× (چند نوع قاعده، یک سرویس) | Strategy + Composite + Specification + Factory | مطالعهٔ موردی همانطور که نوشته شد |
| ۱۰۰× (تیمهای زیاد، قواعد از شرکا) | Registry با extend()، مجموعهقواعد نسخهدار، سرویس جدا، تست قرارداد، cache با بررسی نسخه | ACL، outbox، saga هرجا لازم |
در هر گام قاعدهٔ راهنما یکی است: وقتی نیروی نامدار پیدا شد الگو اضافه کنید و تصمیم را بنویسید.
آزمایشگاه: ممیزی و refactoring
آمادهسازی: snippetها در docs/snippets/design/patterns-in-practice/go هستند. همهٔ دستورها از همین پوشه اجرا میشوند.
cd docs/snippets/design/patterns-in-practice/go
go vet ./... && go test ./...
# expected: ok for pricing, migrate, combos/decoratorchain, combos/commandmemento- مطالعهٔ موردی را اجرا کنید.
go test ./pricing -run TestFactoryBuildsTreeAndEngineQuotes -v. انتظار: PASS؛ جمع جزء ۸۰۰۰، تخفیف ۱۹۰۰، مجموع ۶۱۰۰. - نوع قاعدهٔ تازه بدون ویرایش factory. در یک فایل تازه در package
pricingقاعدهٔFreeShippingبنویسید و در یک تستf.Register("free_shipping", ...)را صدا بزنید. انتظار: factory آن را میسازد؛factory.godiff ندارد. - عمداً خلوص را بشکنید. در
PercentOff.Applyیکtime.Now()به یک شرط اضافه کنید. انتظار:TestSpecificationsو تستهای قیمت به زمان وابسته میشوند؛ برگردانید و ساعت را درCart.Nowنگه دارید. - تزیین را بشمارید.
grep -rEn "type [A-Za-z]*(Manager|Factory|Helper|Impl)\b" --include=*.go . | wc -l. انتظار:Factoryیک بار (registry)؛ هیچ چیز دیگر. - تست قرارداد را اجرا کنید.
go test ./migrate -run TestParity -v. انتظار: PASS: adapterهای local و remote موافقاند. در تست یک درصد را فقط در یکی از engineها عوض کنید و شکستنش را ببینید. - یک strategy بیخون را inline کنید.
antipatterns/before/before.goرا باز کنید،TaxStrategyوFlatTaxStrategyرا حذف وfunc Taxرا اضافه کنید. انتظار: هیچ چیز دیگر تغییر نمیکند؛ فایل کوچکتر میشود.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| طراحی خوب الگوی زیاد دارد | طراحی خوب کمترین قطعه را دارد که تغییر بعدی را جذب کند |
| الگوها را باید از پیش اعمال کرد | اغلب بهتر است وقتی حالت دوم یا سوم آمد با refactoring به آنها رسید |
| هر interface برای هر حالت یک کلاس پیادهسازی میخواهد | در Go یک نوع func میتواند interface را برآورده کند؛ در PHP driver مبتنی بر closure هم خوب است |
factory همیشه از new بهتر است | factory فقط وقتی میارزد که نوعی را انتخاب یا invariantی را اعمال کند |
| Singleton الگوی درست برای config است | container یا مقدار تزریقشده؛ static یک global پنهان است |
| Observer همهچیز را جدا میکند | جریان کنترل را پنهان میکند؛ کار مرتب هماهنگی صریح میخواهد |
| Visitor پاسخ افزودن عملیات است | فقط اگر مجموعهٔ نوعهای گره پایدار باشد |
| میکروسرویس الگوهای تازه میخواهد | همان الگوها را بهعلاوهٔ timeout، idempotency و جبران میخواهد |
| CQRS پیشفرض عادی است | Fowler: "for most systems CQRS adds risky complexity" |
| ADR فرایند سنگین است | یک صفحه، یکبار نوشته میشود و بحث بعدی را ذخیره میکند |
استفاده از Manager فریمورک «تمیز نیست» | همان الگوست که برایتان نگهداری میشود |
چکیده
| موضوع | چه چیزی را به یاد داشته باشید |
|---|---|
| انتخاب | مسئله، نیروها، نامزدها، پیامدها، سادهترین گزینهٔ کارآمد |
| نامزد اول | کد ساده (تابع، switch، map) |
| کی seam اضافه کنیم | حالت سوم، تیم دوم، یا وابستگی کند در تست |
| Factory + Strategy | نام الگوریتم را انتخاب میکند؛ Manager در Laravel، map از funcها در Go |
| Decorator + Chain | middleware؛ هر حلقه میتواند زنجیره را متوقف کند |
| Command + Memento | Undo؛ وقتی معکوس ارزان نیست snapshot |
| Observer + Mediator | رویدادها؛ فقط واکنشهای بیترتیب |
| Composite + Visitor | درخت بهعلاوهٔ عملیات؛ Visitor فقط برای درخت پایدار |
| Builder + Director | گامها بهعلاوهٔ دستورپختهای نامدار |
| Proxy + Flyweight | تنبل و مشترک؛ فقط اشیای تغییرناپذیر |
| نشانههای بیشطراحی | یک پیادهسازی برای هر interface، کلمهٔ الگو در اسمها، factory دور new |
| Refactoring | گامهای کوچک، تست سبز، فهرست Kerievsky |
| مقیاس سرویس | Gateway، ACL، Sidecar، Outbox، Saga: همان ایدهها با یک شبکه |
| مستندسازی | ADR یکصفحهای: زمینه، تصمیم، پیامدها، محرک بازبینی |
| تست | تست نقش، تست composite، تست خطای factory، تست سیمکشی، تست قرارداد |
| استخراج | اول port، دو adapter، تست قرارداد، بعد مسیریابی ترافیک |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — پنج گام روش انتخاب چیست و کدام پیش از نامزدها میآید؟ مهم
پاسخ
پاسخ: مسئله، نیروها، الگوهای نامزد، پیامدها، سادهترین گزینهٔ کارآمد. پرسش «آیا کد ساده کافی است؟» پیش از فهرست کردن هر الگو میآید.
۲ — چهار هزینهای را که Fowler به ویژگیهای حدسی نسبت میدهد نام ببرید. تکمیلی
پاسخ
پاسخ: Cost of build، cost of delay، cost of carry، cost of repair.
۳ — Illuminate\Support\Manager کدام دو الگو را ترکیب میکند و driver را کجا اضافه میکنید؟ مهم
پاسخ
پاسخ: Factory و Strategy. در زیرکلاس یک متد createXxxDriver اضافه میکنید، یا هنگام اجرا extend($driver, $callback) را صدا میزنید. createDriver() اول creatorهای سفارشی را امتحان میکند.
۴ — Pipeline::then() در Laravel زنجیره را چطور میسازد؟ مهم
پاسخ
پاسخ: روی pipeهای برعکسشده array_reduce با carry() اجرا میکند و closureهای تودرتو میسازد؛ هر pipe مقدار و یک closure به نام $next میگیرد.
۵ — دو نشانهٔ Strategy بیخون و درمانش را بگویید. مهم
پاسخ
پاسخ: یک پیادهسازی، بدون state، بدون حالت دوم برنامهریزیشده. درمان: تابع ساده؛ وقتی حالت دوم آمد interface استخراج کنید.
۶ — چرا Group یک Composite است و چرا موتور قیمت را دادهمحور میکند؟ مهم
پاسخ
پاسخ: Group یک Rule است که Ruleها را نگه میدارد، پس درختهایی با هر شکل یک Ruleاند. Factory درخت را از تعریفهای ذخیرهشده میسازد، پس بیشتر تغییرها ردیف دادهاند.
۷ — Specification چه چیزی را جدا میکند؟ مهم
پاسخ
پاسخ: "how to match a candidate" را از نامزدی که مطابقت داده میشود، تا شرطها ترکیبپذیر و دوبارهقابلاستفاده باشند.
۸ — کدام الگوها از استخراج بدون تغییر جان سالم به در میبرند و کدام به قرارداد شبکه تبدیل میشوند؟ مهم
پاسخ
پاسخ: Strategy، Composite، Specification و Factory داخل سرویس میمانند. Facade به API، Adapter به ACL، Proxy به کلاینت راهدور، Observer به رویداد بهعلاوهٔ outbox، Command به پیام با کلید idempotency و Mediator به saga تبدیل میشود.
۹ — چرا ساعت در Cart.Now است؟ مهم
پاسخ
پاسخ: تا قواعد خالص و قیمتها تکرارپذیر باشند؛ تستها به ساعت دیواری وابسته نمیشوند.
۱۰ — یک ADR چه دارد و چقدر باید باشد؟ حیاتی
پاسخ
پاسخ: عنوان، زمینه، تصمیم، وضعیت، پیامدها (همهشان)، یک یا دو صفحه (Nygard).
۱۱ — تست قرارداد بین adapterهای Local و Remote از چه چیزی محافظت میکند؟ مهم
پاسخ
پاسخ: اینکه انتقال pricing به یک سرویس قیمتها را عوض نکند؛ دو adapter برای یک cart باید موافق باشند.
واژهنامه
| اصطلاح | یک خط |
|---|---|
| نیرو (Force) | فشار روی طراحی: منبع تغییر، قید یا هدف کیفی |
| پیامد (Consequence) | هزینه یا فایدهای که از انتخاب الگو برمیآید |
| الگوی نامزد (Candidate pattern) | یکی از دو یا سه پاسخ ممکن به همان نیروها |
| سادهترین گزینهٔ کارآمد (Simplest that works) | گزینهای با کمترین قطعه که تغییر نامبردهشدهٔ بعدی را جذب کند |
| زبان الگو (Pattern language) | مجموعهای از الگوها که به یک دامنه میخورند و به ترتیب اعمال میشوند |
| Factory + Strategy | factory الگوریتم را با نام انتخاب میکند؛ strategy محاسبه میکند |
| Decorator + Chain | رفتارهایی که یکدیگر را میپیچند و هرکدام میتواند فراخوانی را متوقف کند |
| Command + Memento | کنشهای برگشتپذیر که وقتی معکوس نیست snapshot را بازمیگردانند |
| Observer + Mediator | هابی که اشتراکها را دارد تا اجزا هرگز به هم ارجاع ندهند |
| Composite + Visitor | درخت و عملیات روی آن بدون ویرایش گرهها |
| Builder + Director | ساخت گامبهگام بهعلاوهٔ دستورپختهای نامدار |
| Proxy + Flyweight | بارگذار تنبل که اشیای مشترک و تغییرناپذیر میدهد |
| Specification | شیئی که به «آیا این نامزد جور است؟» جواب میدهد و با دیگران ترکیب میشود |
| Strategy | الگوریتمهای قابلتعویض پشت یک interface |
| Composite | درختی که در آن گروه مثل یک عنصر استفاده میشود |
| Registry | نگاشت نام به سازنده یا نمونه |
| YAGNI | "You Aren't Gonna Need It": ویژگی حدسی نسازید |
| عمومیتدهی حدسی (Speculative generality) | قلاب و انتزاع «شاید لازم شد» |
| ویژگی حدسی (Presumptive feature) | اصطلاح Fowler برای کدی که ویژگیای را پشتیبانی میکند که هنوز استفاده نمیشود |
| هزینهٔ نگهداری (Cost of carry) | پیچیدگی مداوم از ویژگیای که هنوز استفاده نمیشود |
| چگالی الگو (Pattern density) | ساختار حملشده بهازای واحد رفتار |
| سوءاستفاده از Singleton (Singleton abuse) | global پنهان بهجای وابستگی تزریقشده |
| انفجار Factory (Factory explosion) | یک factory برای هر کلاس از سر عادت |
| Strategy بیخون (Anemic strategy) | strategy با یک بدنه و بدون تنوع |
| Mediator خدا (God mediator) | mediator که همهٔ قواعد همهٔ اجزا را دارد |
| Refactoring به الگو (Refactoring to patterns) | رسیدن به الگو با گامهای کوچک از کد کارکن (Kerievsky) |
| ADR | Architecture Decision Record: زمینه، تصمیم، وضعیت، پیامدها |
| لایهٔ ضدفساد (Anti-corruption layer، ACL) | adapter که مفهومهای مدل دیگر را از مدل شما بیرون نگه میدارد |
| Gateway | نقطهٔ ورود واحد که مسیریابی، احراز هویت و شکلدهی ترافیک میکند |
| Sidecar | مؤلفهٔ کمکی در پردازهٔ جدا که چرخهٔ عمر اپ را شریک است |
| Outbox | پیامهایی که در همان تراکنش داده ذخیره و بعداً منتشر میشوند |
| Saga | دنبالهٔ هماهنگشدهٔ تراکنشهای محلی با جبران |
| CQRS | مدل جدا برای نوشتن و خواندن |
| Strangler fig | جایگزینی تدریجی پشت یک facade مسیریاب |
| تست قرارداد (Contract test) | تستی که نشان میدهد دو پیادهسازی یک port موافقاند |
| الگوی فریمورک (Framework pattern) | الگویی که اسکلتش مال فریمورک است |
| الگوی اپلیکیشن (Application pattern) | الگویی که برای دامنهٔ شما ساخته شده |
منابع
- Martin Fowler, "Yagni", martinfowler.com, 26 May 2015. martinfowler.com/bliki/Yagni.html
- Michael Nygard, "Documenting Architecture Decisions", 15 November 2011. cognitect.com
- Joshua Kerievsky, Refactoring to Patterns, catalogue of 27 refactorings. industriallogic.com/refactoring-to-patterns/catalog, Replace Conditional Logic with Strategy, Form Template Method, Unify Interfaces with Adapter, Introduce Polymorphic Creation, Extract Composite
- Eric Evans and Martin Fowler, "Specifications". martinfowler.com/apsupp/spec.pdf
- refactoring.guru: Strategy, Decorator, Composite, Memento, Mediator, Flyweight, Speculative Generality. منبع ثانویه برای نیتهای GoF (خود کتاب GoF برای این صفحه خوانده نشد).
- Martin Fowler, CQRS, Strangler Fig
- Chris Richardson, Saga, Transactional outbox
- Microsoft Azure Architecture Center: Anti-Corruption Layer, Sidecar, Gateway Routing
- Go source: net/http/server.go, io/io.go, sort/sort.go, database/sql/driver/driver.go
- Laravel framework source (13.x): Container.php, Pipeline.php, Dispatcher.php, Query/Builder.php, ChannelManager.php, FilesystemManager.php, Support/Manager.php, Facades/Pipeline.php
- Laravel 13 docs: Service container, Notifications, Filesystem, Events, Contracts