Structural Patterns: Facade, Adapter, Composite, Proxy, Decorator, Bridge, Flyweight
"Structural patterns are concerned with how classes and objects are composed to form larger structures." — Gamma، Helm، Johnson، Vlissides، Design Patterns: Elements of Reusable Object-Oriented Software، فصل 4 (۱۹۹۴)
خلاصه (Summary): هفت الگوی ساختاری GoF هفت راه برای گذاشتن یک شیء جلوی، دورِ یا کنار شیء دیگر هستند: برای ساده کردن (Facade)، برای ترجمه (Adapter)، برای اینکه یک درخت مثل یک چیز رفتار کند (Composite)، برای نگهبانی (Proxy)، برای اضافه کردن یک لایه (Decorator)، برای جدا کردن دو بُعد (Bridge) و برای اشتراک (Flyweight). تمرکز (Focus): نیت، مسئله، ساختار، شرکتکنندهها، پیامدها و «کی استفاده نکنیم» برای هر الگو؛ تفاوت دقیق Adapter، Bridge، Decorator، Proxy و Facade؛ wrapperهای io در Go، middlewareهای http.Handler و httputil.ReverseProxy؛ facadeهای Laravel که در واقع static proxy هستند، Container::extend، adapterهای cache و Flysystem، کانالهای notification و lazy objectهای PHP 8.4؛ و همین ایدهها در مقیاس سرویس (API gateway، anti-corruption layer، sidecar، decoratorهای retry و circuit breaker). هدف یادگیری (Learning goal): به یک wrapper در کد واقعی نگاه کنید، بگویید کدام یک از این هفت است (یا ترکیب کدام دو)، توضیح دهید چه هزینهای در allocation، هویت شیء و قابلیت دیباگ دارد، و دو شکلی را که در production بیشتر از همه میبینید بسازید: یک زنجیرهٔ decorator دور یک HTTP client و یک anti-corruption layer دور یک API قدیمی.
این صفحه مرجع کامل خانوادهٔ ساختاری در کاتالوگ Gang of Four است. ریشهٔ الگوها و سه خانواده در مقدمهٔ الگوهای طراحی آمده؛ الگوهای ساخت شیء (Factory Method، Builder، Singleton و…) در الگوهای سازنده؛ Chain of Responsibility و Strategy و Observer که بعضی از این wrapperها شبیهشان هستند در الگوهای رفتاری؛ و ترکیب الگوها و افراط در الگو در الگوها در عمل. خودِ ترکیب اشیاء و اینکه چرا «فقط با دوستانت حرف بزن» مهم است در ترکیب اشیاء و قانون Demeter است. صفحههای SOLID توضیح میدهند چرا این الگوها کار میکنند: Open–Closed (رفتار اضافه کن بدون ویرایش)، Liskov Substitution (wrapper باید قراردادِ چیزی را که میپوشاند رعایت کند)، Interface Segregation (interface کوچک راحت wrap میشود) و Dependency Inversion (adapterها portی را پیاده میکنند که هستهٔ برنامه مالکش است).
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| هر هفت الگو در سه جدول | همهچیز در یک دقیقه |
| چرا اصلاً ساختار مبتنی بر ترکیب لازم است | چرا الگوهای ساختاری وجود دارند |
| GoF ۱۹۹۴، مقایسههای خود فصل، تاریخچهٔ بعدی | از کجا آمده |
| یک الگو با عمق کامل (نیت، ساختار، کد، پیامد) | Facade، Adapter، Composite، Proxy، Decorator، Bridge، Flyweight |
| Adapter در برابر Bridge در برابر Decorator در برابر Proxy در برابر Facade | تشخیص wrapperها از هم |
| معادلها در Java، .NET، TypeScript و Python | نگاه هر زبان |
interfaceهای گمشده، ترتیب wrapperها، Unwrap، __callStatic، extend، benchmark | سازوکار |
| نقشهٔ stdlib در Go و فریمورک در Laravel | Go، Laravel |
| قفل شدن به vendor، دغدغههای سراسری، N+1، انفجار کلاس | حل مسئلههای کلاسیک |
| کدام الگو برای کدام وضعیت | انتخاب |
| API gateway، ACL، sidecar، caching proxy | در معماری |
| آزمایشگاه زنجیرهٔ decorator و ACL | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، همهٔ اصطلاحها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
هر هفت الگو به زبان ساده. هر سطر در بخش الگوها باز میشود.
| الگو | به زبان ساده | نیت GoF (کوتاه) | مثال Go | مثال Laravel / PHP |
|---|---|---|---|---|
| Facade (نما) | یک در ساده به یک اتاق شلوغ | "unified interface to a set of interfaces in a subsystem" | http.Get جلوی Client، Transport، Request | یک CheckoutService جلوی موجودی، پرداخت و ارسال |
| Adapter (مبدل) | تبدیل دوشاخهٔ برق | "Convert the interface of a class into another interface clients expect" | http.HandlerFunc؛ structی که SDK یک vendor را با interface شما جور میکند | adapterهای Flysystem، storeهای cache، LegacySmsAdapter |
| Composite (مرکب) | پوشهای که مثل فایل جواب میدهد | "treat individual objects and compositions of objects uniformly" | درخت فایل، AST، io.MultiWriter (یک writer ساخته از چند writer) | درخت منو، یک rule ساخته از چند rule |
| Proxy (نماینده) | جانشینی که تصمیم میگیرد چیز واقعی را صدا بزند یا نه | "surrogate or placeholder for another object to control access to it" | httputil.ReverseProxy، wrapper کش، مقداردهی تنبل با sync.OnceValues | facadeهای Laravel («static proxy»)، lazy proxyهای PHP 8.4، repositoryهای کشدار |
| Decorator (تزئینگر) | لایهای که یک کار اضافه میکند و فراخوانی را رد میکند | "Attach additional responsibilities to an object dynamically" | bufio.NewWriter(gzip.NewWriter(f))، middlewareهای http.Handler | middlewareهای HTTP، Container::extend، middlewareهای Guzzle |
| Bridge (پل) | دو پیچ مستقل به جای یک پیچ برای هر ترکیب | "Decouple an abstraction from its implementation so that the two can vary independently" | database/sql (API) × driver.Driver (پیادهسازی) | Notification × channel، API Storage × adapter Flysystem |
| Flyweight (سبکوزن) | بخش سنگین و یکسان را شریک شو؛ بقیه را پاس بده | "Use sharing to support large numbers of fine-grained objects efficiently" | unique.Make (interning)، یک map از styleهای مشترک | caseهای enum (شیء singleton)، یک pool استاتیک برای style |
خانوادهٔ wrapperها در یک نگاه. پنج تا از هفت الگو چیزی را میپوشانند. این چهار سؤال آنها را از هم جدا میکند (نسخهٔ کامل: تشخیص wrapperها از هم).
| سؤال | Facade | Adapter | Proxy | Decorator | Bridge |
|---|---|---|---|---|---|
| کلاینت interfaceی متفاوت از شیء پوشیدهشده میبیند؟ | بله، یک interface تازه و سادهتر | بله، همانی که کلاینت از قبل انتظارش را دارد | نه، یکسان | نه، یکسان | interface خودِ abstraction |
| پشتش چند شیء است؟ | چندتا (یک زیرسیستم) | معمولاً یکی | یک subject | یک component (که شاید خودش پوشیده باشد) | یک implementor |
| برای روی هم چیدن طراحی شده؟ | نه | بهندرت | بهندرت | بله، اصل ماجرا همین است | نه |
| کِی طراحی میشود؟ | هر وقت | بعد از واقعه، برای جور کردن کد موجود | هر وقت | هر وقت | از اول، قبل از اینکه سلسلهمراتبها بزرگ شوند |
جایی که همین حالا از آنها استفاده میکنید.
| سطح | Go | Laravel / PHP |
|---|---|---|
| کتابخانهٔ استاندارد | io، bufio، compress/gzip، net/http، httputil، database/sql، unique | Illuminate\Support\Facades، Illuminate\Container، Illuminate\Http\Client، Flysystem، PSR-7/15/18 |
| کد خودتان | port و adapter، middleware، decorator دور clientها | کلاسهای سرویس، middleware، extend، درایورهای سفارشی cache و filesystem، کانالهای notification |
| بین سرویسها | reverse proxy، API gateway، sidecar (Envoy)، anti-corruption layer | همانها، با Laravel بهعنوان یکی از سرویسها |
چرا الگوهای ساختاری وجود دارند
بیشتر کدهای واقعی به این دلیل خراب نمیشوند که یک کلاس غلط است؛ خراب میشوند چون کلاسها غلط به هم وصل شدهاند: controllerی که یازده کلاس از SDK پرداخت را میشناسد، typeِ یک vendor که به همهٔ ماژولها نشت کرده، یک زیرکلاس برای هر ترکیبی از قابلیتها، درختی که در سی جا با if ($node instanceof Folder) پیمایش میشود، یا یک میلیون شیء که هر کدام همان 4 کیلوبایت دادهٔ تکراری را حمل میکنند. الگوهای ساختاری کاتالوگ اتصالهای خوب هستند. به گفتهٔ GoF همهشان از دو سازوکار استفاده میکنند: وراثت (Inheritance) برای الگوهای کلاسی و ترکیب اشیاء (Object composition) برای الگوهای شیئی. Go وراثت ندارد، پس هر الگوی ساختاری در Go همان شکل شیئی (ترکیبی) است.
| ساختار مبتنی بر وراثت | ساختار مبتنی بر ترکیب |
|---|---|
| در زمان کامپایل ثابت است | در زمان اجرا قابل چیدمان دوباره است ("change the composition at run-time, which is impossible with static class composition"، GoF) |
| یک زیرکلاس برای هر ترکیب قابلیت | یک type کوچک برای هر قابلیت، آزادانه ترکیبشدنی |
| فرزند جزئیات داخلی والد را میبیند (استفادهٔ جعبهسفید) | wrapper فقط interface را میبیند (استفادهٔ جعبهسیاه) |
| شیء کمتر، یک فراخوانی مستقیم | شیء بیشتر، یک فراخوانی رد کردنی برای هر لایه |
| خواندنش در یک فایل آسان است | رفتار روی زنجیره پخش است؛ باید سیمکشی را بدانید |
| در Go وجود ندارد | تنها گزینه در Go: interface + struct + embedding |
این تصویر کوتاهترین روال تصمیمگیری این صفحه است: اول بپرسید wrapper interface را عوض میکند یا نه؛ بعد اینکه یک زیرسیستم را میپوشاند یا یک شیء را؛ بعد اینکه رفتار اضافه میکند یا دسترسی را کنترل میکند. Bridge جدا ایستاده، چون شکافی است که قبل از نوشتن کد طراحی میکنید، نه wrapperی که بعداً اضافه میشود.
تشبیهی که در کل صفحه تکرار میکنیم: اقامت در یک هتل در کشوری دیگر. کانسیرژ هتل تاکسی و میز رستوران و بلیت را با یک درخواست رزرو میکند: یک Facade روی شهری پر از سرویس. تبدیل دوشاخه در کیف شما شارژر لپتاپ را با پریز دیوار جور میکند: یک Adapter. کارت کلید اتاق جانشین اتاق است و چک میکند شما کی هستید: یک Proxy. گوشی در قاب باتریدار در کیسهٔ ضدآب هنوز همان گوشی است، با دو لایهٔ اضافه: Decoratorها. هتل به سؤال «چند مهمان دارید؟» برای یک اتاق، یک طبقه یا کل ساختمان یکجور جواب میدهد: یک Composite. کنترل تلویزیون با هر تلویزیونی که همان پروتکل مادونقرمز را بفهمد کار میکند و سازندهٔ تلویزیون کنترل را طراحی نکرده: یک Bridge (کنترل × تلویزیون). و هتل یک طرح نقشهٔ شهر را برای 10,000 مهمان چاپ میکند و فقط شمارهٔ اتاق هر مهمان را رویش علامت میزند: یک Flyweight.
سه بدفهمی رایج، از همین اول
- «facadeهای Laravel همان الگوی Facade هستند.» مستندات خود Laravel آنها را «static proxies» به bindingهای container مینامد.
Cache::get()زیرسیستمی را ساده نمیکند؛ یک فراخوانی را به یک شیء رد میکند. این یک Proxy است (بهاضافهٔ Service Locator). Facadeِ GoF کلاسی است که خودتان جلوی چند کلاس مینویسید. ببینید facadeهای Laravel، static proxy هستند. - «Decorator و Proxy و Adapter یک چیزند: wrapper.» ساختارشان مشترک است و بحث خود GoF میگوید این شباهت "belie[s] the different intents". Adapter interface را عوض میکند؛ Decorator آن را نگه میدارد و رفتار اضافه میکند و برای روی هم چیدن است؛ Proxy آن را نگه میدارد و دسترسی به یک subject را کنترل میکند. نیت است که اسم را تعیین میکند، چون نیت تعیین میکند توسعهدهندهٔ بعدی چه چیزی را با خیال راحت میتواند عوض کند.
- «الگوهای ساختاری دربارهٔ کاراییاند.» فقط Flyweight اینطور است. بقیه کمی هزینه دارند (یک فراخوانی اضافه، گاهی یک allocation برای هر wrap) و در عوض تغییرپذیری میدهند. اگر profile گفت یک wrapper داغ است، اندازه بگیرید؛ benchmarkهای پایین نشان میدهند یک زنجیرهٔ پنجلایهٔ decorator در Go چند نانوثانیه برای هر فراخوانی هزینه دارد.
از کجا آمده
۱۹۹۴، کتاب GoF. فصل 4 کتاب Design Patterns (Gamma، Helm، Johnson، Vlissides) هفت الگوی ساختاری را به ترتیب الفبا میآورد: Adapter، Bridge، Composite، Decorator، Facade، Flyweight، Proxy. آنها را به الگوهای کلاسی که "use inheritance to compose interfaces or implementations" (فقط شکل کلاسی Adapter) و الگوهای شیئی که "describe ways to compose objects to realize new functionality" تقسیم میکند. هفت نیت، کلمهبهکلمه، همان سطرهای «تعریف» در بخش الگوها هستند.
فصل با بحثی تمام میشود که هنوز بهترین راه تشخیص این الگوها از هم است. دربارهٔ Adapter و Bridge:
"The Adapter pattern makes things work after they're designed; Bridge makes them work before they are." — GoF، Design Patterns، Discussion of Structural Patterns
دربارهٔ Facade در برابر Adapter میگوید facade "defines a new interface, whereas an adapter reuses an old interface". دربارهٔ Decorator در برابر Proxy: "In the Proxy pattern, the subject defines the key functionality, and the proxy provides (or refuses) access to it. In Decorator, the component provides only part of the functionality, and one or more decorators furnish the rest." و دربارهٔ Composite در برابر Decorator: "From the point of view of the Decorator pattern, a composite is a ConcreteComponent. From the point of view of the Composite pattern, a decorator is a Leaf."
دهههای ۲۰۰۰ و ۲۰۱۰، الگوها به زیرساخت مهاجرت میکنند. همین شکلها در مقیاس شبکه ظاهر میشوند. کتاب Domain-Driven Design اریک ایوانز نام لایهٔ ضدفساد (Anti-corruption layer) را میگذارد؛ Azure Architecture Center مایکروسافت آن را "a facade or adapter layer between different subsystems that don't share the same semantics" توصیف میکند. reverse proxyها، API gatewayها ("Gateway routing. You can use an API gateway as a reverse proxy…"، Azure Architecture Center) و sidecar ("Like a motorcycle sidecar, these components attach to a parent application and share its life cycle") همان Proxy و Decorator هستند که بینشان شبکه افتاده. Envoy خودش را "an L7 proxy and communication bus" با "out of process architecture" معرفی میکند.
Go. جفت io.Reader/io.Writer الگوی Decorator را راه عادی ساختن I/O کرد: bufio "wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface". net/http adapter تابعی را مشهور کرد: "The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers." Go 1.20 نوع httputil.ProxyRequest و hook ِ Rewrite را اضافه کرد (و Director قدیمی حالا با "Deprecated: Use Rewrite instead" علامت خورده)، همراه با http.ResponseController که از wrapperها میخواهد متد Unwrap داشته باشند. Go 1.21 تابع sync.OnceValues را آورد که یک virtual proxy آماده برای مقداردهی اولیه است. Go 1.23 package ِ unique را برای "canonicalizing ("interning") comparable values" اضافه کرد: یک Flyweight در کتابخانهٔ استاندارد.
PHP و Laravel. PSR-7 (پیامهای HTTP، تغییرناپذیر: "all methods that might change state MUST be implemented such that they retain the internal state of the current message")، PSR-15 (middleware سمت سرور) و PSR-18 (HTTP client) باعث شدند Adapter و Decorator بین فریمورکها قابلجابهجایی شوند. مستندات Laravel facadeهایش را "static proxies" به سرویسهای container تعریف میکند و HTTP client را "powered by Guzzle" میداند، که middlewareش "is implemented as a higher order function". PHP 8.4 lazy objectهای بومی آورد: "Two lazy object strategies are supported: Ghost Objects and Virtual Proxies". enumهای PHP (از PHP 8.1) یک flyweight درونساختهاند: "each case is backed by a singleton object of that name".
الگوها، یکییکی
هر بلوک یک ترتیب ثابت دارد: به زبان ساده، باور غلط رایج، تعریف GoF، مسئله، ساختار بهصورت تصویر و جدول شرکتکنندهها، یک توالی فراخوانی، سناریوهای واقعی، کد Go، کد Laravel، پیامدها و اینکه کی استفاده نکنیم.
Facade (نما) حیاتی
به زبان ساده: یک کلاس با چند متد روشن، جلوی کلاسهای زیادی که باید به ترتیب درست صدا زده شوند. همان کانسیرژ.
بدفهمی رایج: «facade زیرسیستم را پنهان میکند؛ هیچکس نباید مستقیم سراغش برود.» GoF برعکس میگوید: facade مانع "applications from using subsystem classes if they need to" نمیشود. یک راحتی و یک مرز است، نه دیوار. اگر دیوار میخواهید، زیرسیستم را در package ِ internal/ (در Go) یا ماژولی با API عمومی باریک بگذارید.
تعریف (نیت GoF): "Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use."
مسئله: checkout باید موجودی را رزرو کند، پرداخت را authorize کند، برچسب ارسال بسازد و اگر پرداخت شکست خورد رزرو را برگرداند. بدون facade، هر controller و job و فرمان CLI این ترتیب و این جبران (Compensation) را تکرار میکند و هر کدام سه زیرسیستم را import میکند.
| شرکتکننده (Participant) | نقش | در snippet |
|---|---|---|
| Facade | میداند کدام کلاس زیرسیستم مسئول یک درخواست است؛ واگذار میکند | Checkout / CheckoutFacade |
| کلاسهای زیرسیستم (Subsystem classes) | کار واقعی را انجام میدهند؛ از وجود facade خبر ندارند | Inventory، Payments، Shipping |
| کلاینت (Client) | facade را صدا میزند (یا در صورت نیاز زیرسیستم را) | controller، job، CLI |
Client Checkout (facade) Inventory Payments Shipping
1 PlaceOrder(o) ──▶ Reserve(sku, qty) ──▶ ok res-book
2 Authorize(cust, amt) ─────────────────▶ error "above limit"
3 Release(res-book) ──▶ stock restored
4 ◀── error "checkout: payments: amount above limit" (the client never saw step 3)سناریوی واقعی: یک PaymentService جلوی SDK یک ارائهدهنده با 40 کلاس؛ یک ReportExporter جلوی query builder و کتابخانهٔ PDF و دیسک ذخیرهسازی؛ API عمومی یک ماژول در modular monolith (یک کلاس در هر ماژول که بقیهٔ ماژولها اجازهٔ صدا زدنش را دارند)؛ http.Get(url) در Go که facadeی است روی DefaultClient، NewRequest، Transport و connection pooling؛ «client ساده»ی یک SDK در کنار API سطح پایینش.
Go:
// Facade: one small entry point (Checkout.PlaceOrder) in front of a subsystem
// of inventory, payment and shipping. Callers that need more can still use the
// subsystem types directly; the facade does not hide them, it simplifies.
package main
import (
"context"
"errors"
"fmt"
)
// --- subsystem: three independent parts with their own vocabularies ---
type Inventory struct{ stock map[string]int }
func (i *Inventory) Reserve(_ context.Context, sku string, qty int) (string, error) {
if i.stock[sku] < qty {
return "", fmt.Errorf("inventory: %s: only %d left", sku, i.stock[sku])
}
i.stock[sku] -= qty
return "res-" + sku, nil
}
func (i *Inventory) Release(_ context.Context, reservationID string) { _ = reservationID }
type Payments struct{}
func (Payments) Authorize(_ context.Context, customer string, cents int64) (string, error) {
if cents > 100_000 {
return "", errors.New("payments: amount above limit")
}
return "auth-" + customer, nil
}
type Shipping struct{}
func (Shipping) CreateLabel(_ context.Context, address string) (string, error) {
return "label-for-" + address, nil
}
// --- facade: the one call 90% of callers need ---
type Checkout struct {
inv *Inventory
pay Payments
ship Shipping
}
type Order struct {
Customer, Address, SKU string
Qty int
PriceCents int64
}
type Receipt struct{ Reservation, Authorization, Label string }
// PlaceOrder hides the ordering rules and the compensation: reserve, then
// charge, then ship, and release the reservation if charging fails.
func (c *Checkout) PlaceOrder(ctx context.Context, o Order) (Receipt, error) {
res, err := c.inv.Reserve(ctx, o.SKU, o.Qty)
if err != nil {
return Receipt{}, err
}
auth, err := c.pay.Authorize(ctx, o.Customer, o.PriceCents*int64(o.Qty))
if err != nil {
c.inv.Release(ctx, res)
return Receipt{}, fmt.Errorf("checkout: %w", err)
}
label, err := c.ship.CreateLabel(ctx, o.Address)
if err != nil {
return Receipt{}, fmt.Errorf("checkout: %w", err)
}
return Receipt{res, auth, label}, nil
}
func main() {
c := &Checkout{inv: &Inventory{stock: map[string]int{"book": 3}}}
r, err := c.PlaceOrder(context.Background(), Order{"ada", "Tehran", "book", 2, 1500})
fmt.Println(r, err)
// Output: {res-book auth-ada label-for-Tehran} <nil>
}Laravel: همان facade بهشکل یک کلاس معمولی، و بعد یک facade ِ Laravel (static proxy) که به آن اشاره میکند، تا ببینید این دو کلمه دو معنای متفاوت دارند.
<?php
// 1) A GoF Facade: one class, one simple method, in front of a subsystem.
namespace App\Checkout;
use App\Inventory\InventoryService;
use App\Payments\PaymentGateway;
use App\Shipping\ShippingService;
final class CheckoutFacade
{
public function __construct(
private InventoryService $inventory,
private PaymentGateway $payments,
private ShippingService $shipping,
) {}
public function placeOrder(PlaceOrderData $data): Receipt
{
$reservation = $this->inventory->reserve($data->sku, $data->qty);
try {
$auth = $this->payments->authorize($data->customerId, $data->totalCents());
} catch (\Throwable $e) {
$this->inventory->release($reservation); // compensation lives here, not in controllers
throw $e;
}
return new Receipt(
reservation: $reservation,
authorization: $auth,
label: $this->shipping->createLabel($data->address),
);
}
}
// 2) A Laravel facade is a different thing: a STATIC PROXY to a container binding.
namespace App\Support\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static \App\Checkout\Receipt placeOrder(\App\Checkout\PlaceOrderData $data)
*
* @see \App\Checkout\CheckoutFacade
*/
final class Checkout extends Facade
{
protected static function getFacadeAccessor(): string
{
// Facade::__callStatic() resolves this binding and forwards the call.
return \App\Checkout\CheckoutFacade::class;
}
}
// 3) Using both: the controller calls the static proxy, which reaches the GoF facade.
namespace App\Http\Controllers;
use App\Checkout\PlaceOrderData;
use App\Http\Requests\PlaceOrderRequest;
use App\Support\Facades\Checkout;
use Illuminate\Http\JsonResponse;
final class OrderController
{
public function store(PlaceOrderRequest $request): JsonResponse
{
$receipt = Checkout::placeOrder(PlaceOrderData::fromRequest($request));
return response()->json($receipt, 201);
}
}
// 4) Real-time facade: prefix the import with "Facades\" and any class works statically.
// use Facades\App\Checkout\CheckoutFacade;
// CheckoutFacade::placeOrder($data);
// 5) In tests the static proxy is swappable, which a real static method is not:
// Checkout::shouldReceive('placeOrder')->once()->andReturn($fakeReceipt);پیامدها (Consequences): وابستگی کمتر در کلاینتها (controller به جای سه کلاس یکی را import میکند)؛ زیرسیستم میتواند پشت یک سطح پایدار عوض شود؛ یک جای واحد برای قواعد ترتیب و جبران. هزینه: facadeی که برای هر use case یک متد اضافه میکند به god class تبدیل میشود (ببینید SRP)؛ facadeی که فقط یکبهیک رد میکند لایه اضافه میکند و ارزشی نه.
کی استفاده نکنیم: وقتی کلاینتها واقعاً به انعطاف کامل زیرسیستم نیاز دارند (facade با 30 متد رد کننده یک آینه است، نه سادهسازی)؛ وقتی فقط یک کلاینت هست (inline کنید)؛ وقتی «زیرسیستم» یک کلاس است (آن یا Adapter است یا هیچ).
facadeهای Laravel، static proxy هستند، نه Facadeِ GoF مهم
به زبان ساده: Cache::get('k') یک متد استاتیک نیست. کلاس Cache هیچ متد استاتیکی ندارد. PHP تابع Facade::__callStatic('get', ['k']) را صدا میزند که از container ، binding ِ cache را میگیرد و get را روی آن شیء صدا میزند.
بدفهمی رایج: «facadeها state سراسری استاتیکاند، پس تستپذیر نیستند.» مستندات Laravel جواب داده: facadeها "a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods" میدهند، چون شیء پشتشان قابل تعویض است: Cache::shouldReceive('get')->with('key')->andReturn('value').
تعریف: facade ِ Laravel کلاسی است که از Illuminate\Support\Facades\Facade ارث میبرد و getFacadeAccessor() آن یک کلید container برمیگرداند. در سورس فریمورک، __callStatic کار $instance = static::getFacadeRoot(); … return $instance->$method(...$args); را انجام میدهد و نمونههای resolveشده در static::$resolvedInstance کش میشوند. به زبان GoF این یک Proxy است (همان عملیات subject، هر فراخوانی را رد میکند) که از طریق یک Service Locator به آن میرسیم. یک real-time facade (use Facades\App\Contracts\Publisher;) همین proxy را برای هر کلاسی در لحظه میسازد.
Code Facade (static) Container CacheManager
1 Cache::get('user:42') ──▶ __callStatic('get', [...])
2 getFacadeRoot() ─────────────▶ make('cache') ──▶ (resolved once, cached)
3 $instance->get('user:42') ──────────────────────▶ Redis store ->get()
4 ◀── value
in a test: Cache::shouldReceive('get') swaps step 2's object for a Mockery mock| Facadeِ GoF | facade ِ Laravel | |
|---|---|---|
| پشتش چیست | چند کلاس زیرسیستم | یک binding در container |
| Interface | تازه، سادهتر، سطح بالاتر | همان متدهای شیء پشتش |
| استاتیک؟ | نه، یک شیء معمولی که inject میکنید | بله، syntax استاتیک با __callStatic |
| نزدیکترین الگوی GoF | Facade | Proxy (+ Service Locator) |
| خطر اصلی | رشد تا god class | "class scope creep" (مستندات Laravel): facadeهای زیاد در یک کلاس وابستگیهایش را پنهان میکنند |
Adapter (مبدل) حیاتی
به زبان ساده: یک کلاس کوچک که چیزی با شکل غلط را با شکلی که کد شما انتظار دارد جور میکند. همان تبدیل دوشاخه.
بدفهمی رایج: «adapter یعنی هر کلاسی که یک API بیرونی را صدا میزند.» adapter interfaceی را پیاده میکند که کلاینت از قبل استفاده میکند و به adaptee ترجمه میکند. کلاسی که Stripe را صدا میزند و همان اسم متدهای Stripe را به بقیهٔ برنامه نشان میدهد adapter نیست؛ یک wrapper نازک است که شما را همچنان به Stripe گره میزند.
تعریف (نیت GoF): "Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." نام دیگرش Wrapper است.
مسئله: دامنهٔ شما میگوید SmsSender.Send(ctx, to, text) error. SDK ِ vendor میگوید SubmitMessage(msisdn string, body []byte, flags int) LegacyResult با کدهای عددی، بدون context و شماره تلفن بدون +. نمیتوانید SDK را عوض کنید و نباید بگذارید LegacyResult به checkout نشت کند.
| شرکتکننده | نقش | در snippet |
|---|---|---|
| Target (هدف) | interfaceی که کلاینت استفاده میکند | SmsSender |
| Client | از طریق Target با اشیاء کار میکند | checkout، کد notification |
| Adaptee (تطبیقشونده) | کلاس موجود با interface ناسازگار | LegacySMSClient (SDK ِ vendor) |
| Adapter | Target را پیاده میکند، Adaptee را نگه میدارد، ترجمه میکند | LegacySMSAdapter |
Client Adapter Adaptee (vendor)
1 Send(ctx,"+98912…","…") ──▶ ctx.Err()? no
2 msisdn = "98912…" (strip +, 00)
3 SubmitMessage("98912…", []byte, 0) ──▶ {Code: 17, Msg: "INVALID_DEST"}
4 ◀── error "sms: vendor code 17 (INVALID_DEST)" (client never sees LegacyResult)adapter کلاسی در برابر adapter شیئی (Class adapter vs object adapter) تکمیلی. GoF دو شکل توصیف میکند. class adapter از adaptee ارث میبرد (وراثت private در C++؛ در PHP class Adapter extends Vendor implements Target)؛ میتواند رفتار adaptee را override کند اما به یک کلاس مشخص جوش خورده است. object adapter یک ارجاع به adaptee نگه میدارد؛ با زیرکلاسهای adaptee هم کار میکند و تنها شکل ممکن در Go است. یک two-way adapter هر دو interface را پیاده میکند تا کد قدیم و جدید هر کدام شیء را مال خودشان ببینند. شکل شیئی را ترجیح دهید.
سناریوی واقعی: SDKهای vendor (پیامک، پرداخت، ایمیل، نقشه) پشت port خودتان؛ storeهای cache در Laravel (Redis، Memcached، DynamoDB، database) پشت Illuminate\Contracts\Cache\Store؛ Flysystem ("one interface to interact with many types of filesystems") با adapterهای Local و FTP و SFTP و S3 پشت Storage ِ Laravel؛ clientهای PSR-18 که Guzzle یا Symfony HttpClient را با sendRequest(RequestInterface): ResponseInterface جور میکنند؛ http.HandlerFunc که یک تابع را با interface ِ Handler جور میکند؛ io.NopCloser که یک Reader را به ReadCloser تبدیل میکند؛ درایورهای database/sql.
Go:
// Adapter: make a third-party SDK with the "wrong" shape satisfy the port our
// code owns. Also shows Go's most famous function adapter, http.HandlerFunc.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
// Port: what our application wants (owned by us, named in our language).
type SMSSender interface {
Send(ctx context.Context, to, text string) error
}
// Adaptee: imagine this is github.com/acme/legacysms; we cannot change it.
type LegacySMSClient struct{}
type LegacyResult struct {
Code int // 0 = ok, anything else = vendor error code
Msg string
}
func (LegacySMSClient) SubmitMessage(msisdn string, body []byte, flags int) LegacyResult {
if !strings.HasPrefix(msisdn, "98") {
return LegacyResult{Code: 17, Msg: "INVALID_DEST"}
}
return LegacyResult{Code: 0, Msg: "OK"}
}
// Adapter: implements the port, wraps the adaptee, translates both ways.
type LegacySMSAdapter struct{ client LegacySMSClient }
func (a LegacySMSAdapter) Send(ctx context.Context, to, text string) error {
if err := ctx.Err(); err != nil { // the SDK has no context; we honour ours
return err
}
msisdn := strings.TrimPrefix(strings.TrimPrefix(to, "+"), "00")
res := a.client.SubmitMessage(msisdn, []byte(text), 0)
if res.Code != 0 {
return fmt.Errorf("sms: vendor code %d (%s)", res.Code, res.Msg)
}
return nil
}
// Compile-time check that the adapter satisfies the port.
var _ SMSSender = LegacySMSAdapter{}
func main() {
var s SMSSender = LegacySMSAdapter{}
fmt.Println(s.Send(context.Background(), "+989121234567", "your code is 4821"))
fmt.Println(s.Send(context.Background(), "+15551234567", "hi"))
// Function adapter from net/http: a plain func becomes a Handler.
hello := func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }
var h http.Handler = http.HandlerFunc(hello)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Body.String())
// Output:
// <nil>
// sms: vendor code 17 (INVALID_DEST)
// hello
}Laravel: یک adapter برای SDK که به port شما bind شده، و دو نقطهٔ adapter که Laravel مستند کرده: Cache::extend (یک Store سفارشی) و Storage::extend (یک adapter ِ Flysystem پیچیده در FilesystemAdapter ِ Laravel).
<?php
// 1) Object adapter for a third-party SDK: our port, their client.
namespace App\Notifications\Sms;
interface SmsSender
{
public function send(string $to, string $text): void;
}
final class SmsDeliveryFailed extends \RuntimeException {}
/** Adaptee: a vendor SDK we cannot change (method names, codes and types are theirs). */
final class LegacySmsClient
{
/** @return array{code: int, msg: string} */
public function submitMessage(string $msisdn, string $body, int $flags = 0): array
{
return str_starts_with($msisdn, '98')
? ['code' => 0, 'msg' => 'OK']
: ['code' => 17, 'msg' => 'INVALID_DEST'];
}
}
final class LegacySmsAdapter implements SmsSender
{
public function __construct(private LegacySmsClient $client) {}
public function send(string $to, string $text): void
{
$msisdn = ltrim(preg_replace('/^00/', '', $to), '+');
$result = $this->client->submitMessage($msisdn, $text);
if ($result['code'] !== 0) {
throw new SmsDeliveryFailed("vendor code {$result['code']} ({$result['msg']})");
}
}
}
// 2) Laravel's own adapters: a cache store and a filesystem disk are adapters
// behind one interface (Illuminate\Contracts\Cache\Store, Flysystem's FilesystemAdapter).
namespace App\Providers;
use App\Extensions\MongoStore;
use App\Notifications\Sms\LegacySmsAdapter;
use App\Notifications\Sms\LegacySmsClient;
use App\Notifications\Sms\SmsSender;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
final class AdapterServiceProvider extends ServiceProvider
{
public function register(): void
{
// The rest of the app type-hints SmsSender and never sees the vendor.
$this->app->singleton(SmsSender::class, fn () => new LegacySmsAdapter(new LegacySmsClient));
// Custom cache driver: MongoStore implements Illuminate\Contracts\Cache\Store.
$this->app->booting(function () {
Cache::extend('mongo', fn (Application $app) => Cache::repository(new MongoStore));
});
}
public function boot(): void
{
// Custom disk: a community Flysystem adapter wrapped in Laravel's FilesystemAdapter.
Storage::extend('dropbox', function (Application $app, array $config) {
$adapter = new DropboxAdapter(new DropboxClient($config['authorization_token']));
return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config);
});
}
}
// Callers stay identical whichever adapter is configured:
// Cache::store('mongo')->put('k', 'v', 60);
// Storage::disk('dropbox')->put('invoices/42.pdf', $pdf);پیامدها: vendor قابل تعویض است (adapter دیگری بنویسید)؛ typeهای vendor در adapter متوقف میشوند؛ تستها یک پیادهسازی جعلی از port استفاده میکنند. هزینه: یک type بیشتر؛ ترجمه میتواند اطلاعات را از دست بدهد (خطای غنی vendor به سه نوع خطای شما تبدیل میشود) و این از دست رفتن باید یک تصمیم باشد، نه یک اتفاق.
کی استفاده نکنیم: وقتی «adaptee» کد خودتان است (خودش را عوض کنید)؛ وقتی interfaceها از قبل جورند (interfaceهای ضمنی Go معمولاً adapter را غیرضروری میکنند: اگر type ِ SDK همین حالا Send(ctx, to, text) error دارد، port شما را برآورده میکند)؛ وقتی ترجمه یک نگاشت کامل مدل در یک مرز است: آنوقت یک anti-corruption layer لازم دارید که Adapter بهاضافهٔ Facade بهاضافهٔ یک translator است.
Composite (مرکب) حیاتی
به زبان ساده: یک ظرف و اجزایش به سؤالهای یکسان جواب میدهند، پس صدازننده هرگز نمیپرسد «این یک چیز است یا یک گروه؟». همان هتلی که «چند مهمان؟» را برای اتاق، طبقه یا کل ساختمان جواب میدهد.
بدفهمی رایج: «Composite یعنی هر درختی.» درختی از nodeهای متفاوت که کلاینت باید رویشان switch کند فقط یک درخت است. Composite یعنی interface یکسان: کلاینت روی هر node Size() را صدا میزند و ظرف Size() را با واگذار کردن به فرزندانش پیاده میکند.
تعریف (نیت GoF): "Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly."
مسئله: ابزار محاسبهٔ حجم دیسک، منویی با گروه و آیتم، بستهٔ قیمتی که محصول و بستههای دیگر دارد، مجموعهٔ دسترسی که شامل permission و role است، یک عبارت (2 + 3 + 5) * 4. تا وقتی به برگها و ظرفها یک interface ندهید، همهشان پر از if node is folder then loop else return هستند.
| شرکتکننده | نقش | در snippet |
|---|---|---|
| Component (جزء) | interface همهٔ اشیای درخت | Node، Expr، MenuComponent، ValidationRule |
| Leaf (برگ) | فرزند ندارد؛ کار را انجام میدهد | File، Num، MenuItem، Iban |
| Composite (مرکب) | فرزندان را نگه میدارد؛ عملیات را با واگذاری پیاده میکند | Dir، Sum، MenuGroup، AllOf |
| Client | عملیات Component را صدا میزند | root.Size()، $menu->render($user) |
Client Dir app/ File main.go Dir internal/ File db.go File http.go
1 Size() ──────▶ for children:
2 ├─ Size() ───────▶ 1200
3 └─ Size() ─────────────────────────▶ for children:
4 ├─ Size() ──────▶ 800
5 └─ Size() ─────────────────────▶ 950
6 ◀── 1750
7 ◀── 2950شفافیت در برابر ایمنی (Transparency vs safety) تکمیلی. Add/Remove کجا باشند؟ GoF: "Defining the child management interface at the root of the class hierarchy gives you transparency… It costs you safety, however, because clients may try to do meaningless things like add and remove objects from leaves." اعلام آنها فقط روی Composite ایمنی میدهد و شفافیت را میگیرد. GoF در کتاب شفافیت را انتخاب کرد؛ کد Go تقریباً همیشه ایمنی را انتخاب میکند (Add متدی روی *Dir است نه روی Node)، چون interfaceهای Go عادتاً کوچکاند (ISP).
سناریوی واقعی: فایلسیستمها و «پوشه»های object storage؛ درخت کامپوننتهای UI (کامپوننتهای Blade که کامپوننت دارند، درختهای React)؛ ASTها و query builderها (WHERE (a AND (b OR c)))؛ چارت سازمانی و مراکز هزینه؛ بستههای محصول؛ گروههای دسترسی؛ io.MultiWriter و io.MultiReader در Go (یک writer ساخته از چند writer، یک composite ِ تخت)؛ آرایهٔ ruleها برای هر فیلد در Laravel و یک rule object که چند rule را ترکیب میکند.
Go:
// Composite: leaves and containers share one interface, so client code
// (Size, Eval) never asks "is this a file or a folder?".
package main
import (
"fmt"
"strings"
)
// --- file tree ---
type Node interface {
Name() string
Size() int64
print(b *strings.Builder, depth int)
}
type File struct {
name string
bytes int64
}
func (f File) Name() string { return f.name }
func (f File) Size() int64 { return f.bytes }
func (f File) print(b *strings.Builder, d int) {
fmt.Fprintf(b, "%s%s (%d)\n", strings.Repeat(" ", d), f.name, f.bytes)
}
type Dir struct {
name string
children []Node
}
func (d *Dir) Add(n ...Node) *Dir { d.children = append(d.children, n...); return d }
func (d *Dir) Name() string { return d.name + "/" }
// Size is the composite operation: it delegates to children and sums.
func (d *Dir) Size() int64 {
var total int64
for _, c := range d.children {
total += c.Size()
}
return total
}
func (d *Dir) print(b *strings.Builder, depth int) {
fmt.Fprintf(b, "%s%s (%d)\n", strings.Repeat(" ", depth), d.Name(), d.Size())
for _, c := range d.children {
c.print(b, depth+1)
}
}
// --- expression tree: the same shape, a different domain ---
type Expr interface{ Eval() float64 }
type Num float64
func (n Num) Eval() float64 { return float64(n) }
type Sum []Expr // a composite: any number of children
func (s Sum) Eval() float64 {
var t float64
for _, e := range s {
t += e.Eval()
}
return t
}
type Mul struct{ L, R Expr }
func (m Mul) Eval() float64 { return m.L.Eval() * m.R.Eval() }
func main() {
root := (&Dir{name: "app"}).Add(
File{"main.go", 1200},
(&Dir{name: "internal"}).Add(File{"db.go", 800}, File{"http.go", 950}),
)
var b strings.Builder
root.print(&b, 0)
fmt.Print(b.String())
// (2 + 3 + 5) * 4
fmt.Println(Mul{Sum{Num(2), Num(3), Num(5)}, Num(4)}.Eval())
// Output:
// app/ (2950)
// main.go (1200)
// internal/ (1750)
// db.go (800)
// http.go (950)
// 40
}Laravel: یک درخت منو که گروههایش وقتی کاربر هیچ آیتمی از آنها را نمیبیند ناپدید میشوند، و یک validation rule ِ مرکب.
<?php
// 1) Composite menu: items and groups share one interface.
namespace App\Navigation;
use App\Models\User;
interface MenuComponent
{
/** @return list<array{label: string, url?: string, children?: list<array<string, mixed>>}> */
public function render(User $user): array;
}
final class MenuItem implements MenuComponent
{
public function __construct(
private string $label,
private string $route,
private ?string $ability = null,
) {}
public function render(User $user): array
{
if ($this->ability !== null && $user->cannot($this->ability)) {
return [];
}
return [['label' => $this->label, 'url' => route($this->route)]];
}
}
final class MenuGroup implements MenuComponent
{
/** @var list<MenuComponent> */
private array $children = [];
public function __construct(private string $label) {}
public function add(MenuComponent ...$children): self
{
array_push($this->children, ...$children);
return $this;
}
public function render(User $user): array
{
$rendered = array_merge(...array_map(fn (MenuComponent $c) => $c->render($user), $this->children));
// An empty group disappears: the composite decides, the caller never checks.
return $rendered === [] ? [] : [['label' => $this->label, 'children' => $rendered]];
}
}
// Usage (e.g. in a view composer):
// $menu = (new MenuGroup('Admin'))->add(
// new MenuItem('Orders', 'orders.index', 'viewAny-order'),
// (new MenuGroup('Reports'))->add(new MenuItem('Revenue', 'reports.revenue', 'view-revenue')),
// );
// $tree = $menu->render($request->user());
// 2) Composite validation rule: one rule object made of other rule objects.
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
final class AllOf implements ValidationRule
{
/** @var list<ValidationRule> */
private array $rules;
public function __construct(ValidationRule ...$rules)
{
$this->rules = $rules;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
foreach ($this->rules as $rule) {
$failed = false;
$rule->validate($attribute, $value, function (string $message) use ($fail, &$failed) {
$failed = true;
return $fail($message); // keep the PotentiallyTranslatedString for chaining
});
if ($failed) {
return; // stop at the first failing child, like "bail"
}
}
}
}
final class Iban implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_string($value) || ! preg_match('/^[A-Z]{2}\d{2}[A-Z0-9]{10,30}$/', $value)) {
$fail('The :attribute must be a valid IBAN.');
}
}
}
final class NotSanctioned implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (str_starts_with((string) $value, 'XX')) {
$fail('The :attribute belongs to a blocked country.');
}
}
}
// In a Form Request: 'iban' => ['required', new AllOf(new Iban, new NotSanctioned)],پیامدها: کلاینتها ساده میشوند؛ typeهای برگ و مرکب جدید بدون تغییر کلاینت جا میافتند (Open–Closed). هزینه: طراحی میتواند "overly general" (GoF) شود: محدود کردن یک composite به نوع خاصی از فرزند سخت است و به چک زمان اجرا نیاز دارید؛ درخت عمیق یعنی بازگشت عمیق؛ محاسبهٔ تجمیعی در هر فراخوانی (Size() کل درخت را میپیماید) ممکن است کش با invalidation لازم داشته باشد.
کی استفاده نکنیم: وقتی برگها و گروهها واقعاً interface متفاوت لازم دارند (تحمیل یک interface یعنی متدهای بیاثر زیاد، یک بوی Liskov)؛ وقتی ساختار یک لیست تخت است؛ وقتی درخت در دیتابیس است و عملیات تجمیعی است: یک query بازگشتی SQL معمولاً از بارگذاری درخت در اشیاء سریعتر است.
-- The same "Size of a folder" as one recursive query (WITH RECURSIVE, standard SQL).
WITH RECURSIVE tree AS (
SELECT id, parent_id, size_bytes FROM nodes WHERE id = 1 -- the root "app/"
UNION ALL
SELECT n.id, n.parent_id, n.size_bytes FROM nodes n JOIN tree t ON n.parent_id = t.id
)
SELECT sum(size_bytes) AS total FROM tree; -- 2950Proxy (نماینده) حیاتی
به زبان ساده: جانشینی با دقیقاً همان interface شیء واقعی، که تصمیم میگیرد آیا، کی و چطور آن را صدا بزند. همان کارت کلید اتاق.
بدفهمی رایج: «proxy یک چیز شبکهای است.» proxyهای GoF بیشتر درونپروسهایاند: virtual proxy که ساختن یک شیء گران را عقب میاندازد، protection proxy که دسترسی را چک میکند، smart reference که میشمارد یا کش میکند. reverse proxy ِ شبکه یک نوع از آنهاست (remote proxy) که از بیرون دیده میشود.
تعریف (نیت GoF): "Provide a surrogate or placeholder for another object to control access to it." GoF چهار نوع میشمارد: remote proxy ("a local representative for an object in a different address space")، virtual proxy ("creates expensive objects on demand")، protection proxy ("controls access to the original object") و smart reference (کارهای اضافه هنگام دسترسی: شمارش ارجاع، بارگذاری در اولین استفاده، قفل کردن). ادبیات بعدی caching proxy را بهعنوان یک حالت رایج smart reference اضافه میکند.
مسئله: جستجوی محصول در هر صفحه 400 بار به SQL میخورد؛ یک renderer ِ PDF موقع boot 40 مگابایت فونت بار میکند، حتی در requestهایی که هرگز PDF نمیسازند؛ محصولات منتشرنشده باید برای مشتریها نامرئی باشند؛ کاتالوگ در سرویس دیگری است. در همهٔ این حالتها صدازنندهها باید همچنان Product(id) را صدا بزنند.
| شرکتکننده | نقش | در snippet |
|---|---|---|
| Subject (موضوع) | interface مشترک proxy و شیء واقعی | Catalog |
| RealSubject (موضوع واقعی) | شیئی که کار واقعی را انجام میدهد | dbCatalog، EloquentCatalog |
| Proxy | ارجاعی به RealSubject نگه میدارد و دسترسی را کنترل میکند | CachingCatalog، LazyCatalog، ProtectedCatalog، ReverseProxy |
Client CachingCatalog (proxy) dbCatalog (real)
1 Product(7) ────▶ cache miss
2 next.Product(7) ─────────────────────────▶ SELECT … WHERE id = 7 (5 ms)
3 store {p7, exp = now + 1m}
4 Product(7) ────▶ cache hit, not expired ◀── returns in microseconds; no SQL
5 Product(7) ────▶ cache hit queries after 3 reads: 1سناریوی واقعی: repositoryهای کشدار (با مشکلات invalidation که در Caching آمده)؛ ساخت تنبل سرویس (sync.OnceValues، newLazyProxy در PHP 8.4، سرویسهای lazy در Symfony)؛ wrapperهای مجوزدهی؛ stubهای client در gRPC و SOAP (remote proxy)؛ httputil.ReverseProxy، NGINX، HAProxy و Envoy در لبهٔ شبکه؛ copy-on-write (که GoF آن را یک بهینهسازی smart reference توصیف میکند)؛ lazy loading در ORMها (پایینتر).
Go: proxyهای caching، virtual و protection در یک فایل، و بعد یک remote proxy با reverse proxy ِ کتابخانهٔ استاندارد.
// Proxy: same interface as the real subject, but controls access to it.
// Three kinds from GoF in one file: caching (a smart reference), virtual
// (lazy creation) and protection (authorization).
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
type Product struct {
ID int
Name string
Cents int64
}
// Subject: the interface clients depend on.
type Catalog interface {
Product(ctx context.Context, id int) (Product, error)
}
// RealSubject: slow, e.g. SQL or a remote service.
type dbCatalog struct{ queries int }
func (d *dbCatalog) Product(_ context.Context, id int) (Product, error) {
d.queries++
time.Sleep(5 * time.Millisecond) // pretend network + SQL
return Product{ID: id, Name: fmt.Sprintf("p%d", id), Cents: 990}, nil
}
// --- caching proxy (cache-aside with TTL) ---
type entry struct {
p Product
exp time.Time
}
type CachingCatalog struct {
next Catalog
ttl time.Duration
mu sync.Mutex
m map[int]entry
}
func NewCachingCatalog(next Catalog, ttl time.Duration) *CachingCatalog {
return &CachingCatalog{next: next, ttl: ttl, m: map[int]entry{}}
}
func (c *CachingCatalog) Product(ctx context.Context, id int) (Product, error) {
c.mu.Lock()
e, ok := c.m[id]
c.mu.Unlock()
if ok && time.Now().Before(e.exp) {
return e.p, nil
}
p, err := c.next.Product(ctx, id)
if err != nil {
return Product{}, err // never cache failures here
}
c.mu.Lock()
c.m[id] = entry{p, time.Now().Add(c.ttl)}
c.mu.Unlock()
return p, nil
}
// --- virtual proxy: the expensive subject is built on first use ---
type LazyCatalog struct {
get func() (Catalog, error)
}
func NewLazyCatalog(build func() (Catalog, error)) *LazyCatalog {
return &LazyCatalog{get: sync.OnceValues(build)} // Go 1.21+
}
func (l *LazyCatalog) Product(ctx context.Context, id int) (Product, error) {
c, err := l.get()
if err != nil {
return Product{}, err
}
return c.Product(ctx, id)
}
// --- protection proxy: checks the caller before forwarding ---
type ctxKey struct{}
func WithRole(ctx context.Context, role string) context.Context {
return context.WithValue(ctx, ctxKey{}, role)
}
var ErrForbidden = errors.New("forbidden")
type ProtectedCatalog struct{ next Catalog }
func (p ProtectedCatalog) Product(ctx context.Context, id int) (Product, error) {
if role, _ := ctx.Value(ctxKey{}).(string); role != "staff" && id >= 1000 {
return Product{}, ErrForbidden // ids >= 1000 are unreleased products
}
return p.next.Product(ctx, id)
}
func main() {
db := &dbCatalog{}
var c Catalog = NewCachingCatalog(db, time.Minute)
for range 3 {
_, _ = c.Product(context.Background(), 7)
}
fmt.Println("queries after 3 reads:", db.queries)
built := 0
lazy := NewLazyCatalog(func() (Catalog, error) { built++; return &dbCatalog{}, nil })
fmt.Println("built before first call:", built)
_, _ = lazy.Product(context.Background(), 1)
_, _ = lazy.Product(context.Background(), 2)
fmt.Println("built after two calls:", built)
guarded := ProtectedCatalog{next: c}
_, err := guarded.Product(WithRole(context.Background(), "customer"), 1001)
fmt.Println(err)
// Output:
// queries after 3 reads: 1
// built before first call: 0
// built after two calls: 1
// forbidden
}// A remote proxy at the network level: httputil.ReverseProxy forwards the
// request to a backend and copies the response back. The client cannot tell.
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
)
func main() {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "backend saw path=%s xff=%q", r.URL.Path, r.Header.Get("X-Forwarded-For"))
}))
defer backend.Close()
target, err := url.Parse(backend.URL)
if err != nil {
log.Fatal(err)
}
proxy := &httputil.ReverseProxy{
// Rewrite replaces the deprecated Director hook (see the httputil docs).
Rewrite: func(pr *httputil.ProxyRequest) {
pr.SetURL(target) // scheme, host and base path of the backend
pr.SetXForwarded()
pr.Out.Header.Set("X-Proxy", "academy")
},
ModifyResponse: func(resp *http.Response) error {
resp.Header.Set("X-Served-By", "edge-1")
return nil
},
}
front := httptest.NewServer(proxy)
defer front.Close()
resp, err := http.Get(front.URL + "/orders/42")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body), "|", resp.Header.Get("X-Served-By"))
// Output: backend saw path=/orders/42 xff="127.0.0.1" | edge-1
}Laravel: یک caching proxy و یک protection proxy که interface ِ Catalog را با پیادهسازی Eloquent شریکاند، و یک virtual proxy ساختهشده با lazy objectهای PHP 8.4.
<?php
namespace App\Catalog;
use App\Models\Product;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Auth\Access\AuthorizationException;
// Subject: what callers type-hint.
interface Catalog
{
public function find(int $id): ?Product;
}
// RealSubject: Eloquent + SQL.
final class EloquentCatalog implements Catalog
{
public function find(int $id): ?Product
{
return Product::query()->find($id);
}
}
// 1) Caching proxy (cache-aside). Same interface, fewer queries.
final class CachingCatalog implements Catalog
{
public function __construct(
private Catalog $next,
private Cache $cache,
private int $ttlSeconds = 300,
) {}
public function find(int $id): ?Product
{
// remember() is on the Cache contract; Cache::flexible() adds stale-while-revalidate.
return $this->cache->remember(
"catalog:product:{$id}",
$this->ttlSeconds,
fn () => $this->next->find($id),
);
}
}
// 2) Protection proxy: authorization before forwarding.
final class AuthorizedCatalog implements Catalog
{
public function __construct(private Catalog $next, private Gate $gate) {}
public function find(int $id): ?Product
{
$product = $this->next->find($id);
if ($product !== null && $product->unreleased && $this->gate->denies('view-unreleased')) {
throw new AuthorizationException('Product not released yet.');
}
return $product;
}
}
// 3) Virtual proxy with PHP 8.4 lazy objects: the heavy object is built on first property access.
final class PdfRenderer
{
public function __construct(public readonly string $fontCache)
{
// imagine: loads 40 MB of fonts
}
public function render(string $html): string
{
return "%PDF-1.7 ({$this->fontCache}) ".strlen($html);
}
}
final class LazyFactory
{
public static function pdfRenderer(): PdfRenderer
{
$reflector = new \ReflectionClass(PdfRenderer::class);
return $reflector->newLazyProxy(fn (PdfRenderer $proxy) => new PdfRenderer(storage_path('fonts')));
}
}
// Wiring in a service provider: callers ask for Catalog and get proxy(proxy(real)).
// $this->app->singleton(Catalog::class, fn ($app) => new AuthorizedCatalog(
// new CachingCatalog(new EloquentCatalog, $app->make(Cache::class)),
// $app->make(Gate::class),
// ));
//
// Eloquent's lazy loading is the Lazy Load pattern, a cousin of the virtual proxy:
// $order->customer // first access runs: select * from customers where id = ?
// Turn it into an error outside production (AppServiceProvider::boot):
// Model::preventLazyLoading(! $this->app->isProduction());lazy loading در Eloquent یک Lazy Load ِ شبیه proxy است، و راه کلاسیک خراب شدنش مهم. مستندات Laravel: "Dynamic relationship properties perform "lazy loading", meaning they will only load their relationship data when you actually access them." شیء proxy جداگانهای وجود ندارد (متد جادویی __get ِ model در اولین دسترسی query را اجرا میکند)، پس این الگوی Lazy Load ِ فاولر است نه virtual proxy ِ GoF، اما معامله همان است: صدازننده هزینه را نمیبیند. در یک حلقه، تبدیل به مسئلهٔ N+1 میشود:
-- foreach ($orders as $order) echo $order->customer->name; (50 orders, lazy)
select * from orders limit 50;
select * from customers where customers.id = 17 limit 1;
select * from customers where customers.id = 4 limit 1;
-- … 48 more: 51 queries
-- Order::with('customer')->limit(50)->get(); (eager)
select * from orders limit 50;
select * from customers where customers.id in (4, 17, 23, …); -- 2 queriesModel::preventLazyLoading(! $this->app->isProduction()) query ِ پنهان را در زمان توسعه به exception تبدیل میکند. داستان کامل در ORM Pitfalls است.
پیامدها: صدازنندهها بدون تغییر میمانند در حالی که شما caching، تنبلی، امنیت یا فاصله اضافه میکنید. هزینه: تأخیر پنهان (فراخوانیای که محلی به نظر میرسد ممکن است یک hop شبکه باشد؛ این اولین مغالطهٔ محاسبات توزیعشده است)؛ دادهٔ کهنه در caching proxyها؛ سردرگمی هویت (proxy !== realSubject)؛ و در lazy proxyها خطاها از زمان boot به اولین استفاده منتقل میشوند.
کی استفاده نکنیم: وقتی صدازننده باید از هزینه خبر داشته باشد (فراخوانی راه دور را راه دور نشان دهید: یک ctx، یک timeout، یک error)؛ وقتی cache داستان invalidation ندارد؛ وقتی چک دسترسی به یک policy در لبه تعلق دارد نه به تکتک اشیاء.
Decorator (تزئینگر) حیاتی
به زبان ساده: لایهای با همان interface ِ چیزی که میپوشاند، که قبل یا بعد از رد کردن فراخوانی یک کار اضافه انجام میدهد. لایهها روی هم چیده میشوند. همان گوشی در قاب باتریدار در کیسهٔ ضدآب.
بدفهمی رایج: «@decorator ِ Python و attributeهای PHP همان الگوی Decorator هستند.» decorator ِ تابعی در Python یک تابع مرتبهبالاست که یک تابع را میپوشاند؛ همروح است (و middleware در Go دقیقاً همین شکل را دارد)، اما Decorator ِ GoF دربارهٔ اشیایی است که interface مشترک دارند تا در زمان اجرا ترکیب شوند. attributeهای PHP (#[...]) اصلاً wrapper نیستند، metadata هستند.
تعریف (نیت GoF): "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." نام دیگرش Wrapper است.
مسئله: یک HTTP client به logging، metrics، retry، هدر احراز هویت و circuit breaker نیاز دارد، با ترکیبهای متفاوت در هر جای استفاده. زیرکلاسسازی یعنی LoggingRetryingClient، MeteredRetryingAuthClient… یک کلاس برای هر ترکیب. Decorator یعنی یک کلاس برای هر دغدغه.
| شرکتکننده | نقش | در snippet |
|---|---|---|
| Component | interface | io.Writer، http.Handler، Doer، PaymentGateway |
| ConcreteComponent | شیء واقعی | bytes.Buffer، handler شما، *http.Client، gateway ِ واقعی |
| Decorator | یک Component نگه میدارد، Component را پیاده میکند، رد میکند | countingWriter، Logging(...)، LoggingPaymentGateway |
| ConcreteDecorator | یک مسئولیت اضافه میکند | gzip.Writer، bufio.Writer، RequireHeader، AddSecurityHeaders |
Order of wrapping = order of execution (outermost runs first, finishes last)
h := Logging(RequireHeader(MaxBytes(app)))
1 request ──▶ Logging: start timer
2 ──▶ RequireHeader: header missing → 401, return (app never runs)
3 ◀── Logging: log status=401
swap the two: h := RequireHeader(Logging(MaxBytes(app)))
4 request ──▶ RequireHeader: 401, return → nothing is logged for rejected requestsسناریوی واقعی: I/O در Go (bufio، gzip، io.TeeReader، io.LimitReader، cipher.StreamWriter)؛ middleware سمت سرور در Go و Laravel؛ middleware سمت client (Guzzle، یا wrapper دور RoundTripper یا Doer در Go)؛ wrapperهای retry، timeout، circuit breaker و rate limit؛ logging و metrics دور repositoryها و gatewayها؛ Container::extend در Laravel برای پوشاندن bindingی که کس دیگری ثبت کرده؛ decoratorهای response که هدر اضافه میکنند یا فشرده میکنند.
Go: اول زنجیرهٔ io.Writer (bufio → gzip → writer ِ شمارندهٔ خودمان → buffer، با io.TeeReader که ورودی را hash میکند)، بعد همین ایده بهشکل middleware ِ http.Handler با یک decorator برای ResponseWriter که Unwrap را در اختیار میگذارد.
// Decorator: every wrapper has the SAME interface as what it wraps, adds one
// responsibility, and can be stacked in any order. Go's io and net/http are
// built from this idea.
package main
import (
"bufio"
"bytes"
"compress/gzip"
"crypto/sha256"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"time"
)
// --- part 1: io.Writer decorators from the standard library ---
// countingWriter is our own decorator: it counts bytes, then forwards.
type countingWriter struct {
w io.Writer
n int64
}
func (c *countingWriter) Write(p []byte) (int, error) {
n, err := c.w.Write(p)
c.n += int64(n)
return n, err
}
func compressAndHash(src io.Reader) (compressed int64, sum [32]byte, err error) {
var out bytes.Buffer
counter := &countingWriter{w: &out} // innermost: counts compressed bytes
zw := gzip.NewWriter(counter) // compresses into the counter
bw := bufio.NewWriterSize(zw, 32<<10) // batches small writes before gzip
h := sha256.New()
tee := io.TeeReader(src, h) // hashes the plain text as it is read
if _, err = io.Copy(bw, tee); err != nil {
return 0, sum, err
}
// Close order matters: flush the outer wrapper first, then the inner one.
if err = bw.Flush(); err != nil {
return 0, sum, err
}
if err = zw.Close(); err != nil {
return 0, sum, err
}
copy(sum[:], h.Sum(nil))
return counter.n, sum, nil
}
// --- part 2: http.Handler middleware is the same pattern ---
type Middleware func(http.Handler) http.Handler
// Chain applies the first middleware outermost: Chain(h, a, b) == a(b(h)).
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// statusRecorder decorates http.ResponseWriter to capture the status code.
// Unwrap lets http.ResponseController reach Flush/Hijack on the original.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
func Logging(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Info("http", "method", r.Method, "path", r.URL.Path,
"status", rec.status, "dur_ms", time.Since(start).Milliseconds())
})
}
}
func RequireHeader(name string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(name) == "" {
http.Error(w, "missing "+name, http.StatusUnauthorized)
return // short-circuit: the inner handler never runs
}
next.ServeHTTP(w, r)
})
}
}
func main() {
n, sum, err := compressAndHash(strings.NewReader(strings.Repeat("structural patterns ", 500)))
fmt.Printf("gzip bytes=%d sha256=%x err=%v\n", n, sum[:4], err)
log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey || a.Key == "dur_ms" {
return slog.Attr{} // stable output for the docs
}
return a
},
}))
app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") })
h := Chain(app, Logging(log), RequireHeader("X-Api-Key"),
func(h http.Handler) http.Handler { return http.MaxBytesHandler(h, 1<<20) }, // stdlib decorator
)
for _, key := range []string{"", "k1"} {
req := httptest.NewRequest("GET", "/orders", nil)
if key != "" {
req.Header.Set("X-Api-Key", key)
}
h.ServeHTTP(httptest.NewRecorder(), req)
}
// Output (gzip size depends on the Go version's compressor):
// gzip bytes=80 sha256=73b7d043 err=<nil>
// level=INFO msg=http method=GET path=/orders status=401
// level=INFO msg=http method=GET path=/orders status=200
}Laravel: decoratorهای logging و metrics که با Container::extend روی هم چیده شدهاند، و یک middleware که response را تزئین میکند.
<?php
namespace App\Payments;
use Psr\Log\LoggerInterface;
interface PaymentGateway
{
public function charge(string $orderId, int $amountMinor, string $currency): ChargeResult;
}
// 1) Logging decorator: same interface, adds one responsibility, forwards.
final class LoggingPaymentGateway implements PaymentGateway
{
public function __construct(private PaymentGateway $inner, private LoggerInterface $log) {}
public function charge(string $orderId, int $amountMinor, string $currency): ChargeResult
{
$start = hrtime(true);
try {
$result = $this->inner->charge($orderId, $amountMinor, $currency);
$this->log->info('payment.charge', ['order' => $orderId, 'ok' => $result->approved,
'ms' => intdiv(hrtime(true) - $start, 1_000_000)]);
return $result;
} catch (\Throwable $e) {
$this->log->warning('payment.charge.failed', ['order' => $orderId, 'error' => $e->getMessage()]);
throw $e;
}
}
}
// 2) Metrics decorator: stacks on top of the logging one without either knowing.
final class CountingPaymentGateway implements PaymentGateway
{
public static int $calls = 0;
public function __construct(private PaymentGateway $inner) {}
public function charge(string $orderId, int $amountMinor, string $currency): ChargeResult
{
self::$calls++;
return $this->inner->charge($orderId, $amountMinor, $currency);
}
}
// 3) Container::extend(): decorate a binding without touching who registered it.
namespace App\Providers;
use App\Payments\CountingPaymentGateway;
use App\Payments\LoggingPaymentGateway;
use App\Payments\PaymentGateway;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Psr\Log\LoggerInterface;
final class PaymentDecoratorsProvider extends ServiceProvider
{
public function register(): void
{
// Each extend() wraps the previous result: Counting(Logging(real)).
$this->app->extend(PaymentGateway::class, fn (PaymentGateway $gw, Application $app) =>
new LoggingPaymentGateway($gw, $app->make(LoggerInterface::class)));
$this->app->extend(PaymentGateway::class, fn (PaymentGateway $gw) =>
new CountingPaymentGateway($gw));
}
}
// 4) HTTP middleware is the decorator of the request pipeline;
// this one decorates the RESPONSE after the inner layers ran.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class AddSecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request); // inner layers + controller
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
return $response;
}
}
// bootstrap/app.php:
// ->withMiddleware(function (Middleware $middleware) {
// $middleware->append(AddSecurityHeaders::class);
// })Middleware: Decorator یا Chain of Responsibility؟ تکمیلی هر دو. از نظر ساختاری هر middleware handler ِ بعدی را میپوشاند و همان interface را دارد (Decorator). از نظر رفتاری یک middleware میتواند request را بدون صدا زدن بعدی متوقف کند (PSR-15: "A middleware component MAY create and return a response without delegating to a request handler")، که حرکت تعیینکنندهٔ زنجیرهٔ مسئولیت (Chain of Responsibility) است و در الگوهای رفتاری آمده. مستندات Laravel middleware را "a series of "layers" HTTP requests must pass through" توصیف میکند؛ صفحهٔ Go با نام Middlewares کاتالوگ را پوشش میدهد.
پیامدها: مسئولیتها آزادانه و در زمان اجرا ترکیب میشوند، بدون انفجار زیرکلاس (Open–Closed)؛ هر decorator کوچک و بهتنهایی تستپذیر است. هزینه: "lots of little objects that all look alike" (GoF)، که وقتی زنجیره بلند است دیباگشان سخت است؛ ترتیب مهم است و راحت اشتباه میشود؛ "a decorated component is not identical to the component itself"، پس کدی که هویت را مقایسه میکند یا روی type ِ concrete type assertion میزند میشکند؛ decorator interfaceهای اختیاری چیزی را که میپوشاند پنهان میکند (ببینید سازوکار).
کی استفاده نکنیم: وقتی رفتار اضافه یک قاعدهٔ هستهای است (در خود کلاس بگذارید)؛ وقتی ترتیب لایهها ثابت است و هرگز عوض نمیشود (یک کلاس شاید روشنتر باشد)؛ وقتی باید interface ِ component را عوض کنید (آن Adapter است).
Bridge (پل) مهم
به زبان ساده: وقتی چیزی در دو بُعد تغییر میکند، آن را به دو سلسلهمراتب بشکنید و با یک ارجاع به هم وصل کنید، به جای اینکه برای هر ترکیب یک کلاس بنویسید. همان کنترل و تلویزیون.
بدفهمی رایج: «Bridge همان Adapter با اسم دیگر است.» بحث GoF: "Adapter focuses on resolving incompatibilities between two existing interfaces… Bridge, on the other hand, bridges an abstraction and its (potentially numerous) implementations." Adapter تعمیر است؛ Bridge نقشه است.
تعریف (نیت GoF): "Decouple an abstraction from its implementation so that the two can vary independently." اینجا abstraction یعنی لایهٔ کنترلی سطح بالا که کلاینت استفاده میکند (یک notification، یک کنترل، یک API ِ repository) و implementation (همان Implementor در GoF) یعنی لایهٔ وابسته به پلتفرم که abstraction به آن واگذار میکند (یک transport، یک تلویزیون، یک درایور دیتابیس). منظور «interface در برابر class» نیست.
مسئله: notificationهایی از نوع OrderShipped، SecurityAlert، InvoiceDue، که هر کدام با ایمیل، پیامک، Slack یا push فرستاده میشوند. با زیرکلاسسازی: OrderShippedEmail، OrderShippedSms… یعنی 3 × 4 = 12 کلاس، و کانال پنجم سه کلاس دیگر اضافه میکند. با Bridge: 3 + 4 = 7 type، و کانال پنجم یکی اضافه میکند.
| شرکتکننده | نقش | در snippet |
|---|---|---|
| Abstraction (انتزاع) | API رو به کلاینت؛ یک Implementor نگه میدارد | Notification (با transport) |
| RefinedAbstraction | گونههای abstraction | OrderShipped، SecurityAlert |
| Implementor (پیادهساز) | interface سمت پیادهسازی | Transport.Deliver(to, subject, body) |
| ConcreteImplementor | پیادهسازیهای وابسته به پلتفرم | EmailTransport، SMSTransport، SlackTransport |
Code OrderShipped (abstraction) SMSTransport (implementor)
1 OrderShipped{sms,…}.Send(ctx, to) ──▶ build subject + body (WHAT)
2 transport.Deliver(to, s, b) ──▶ truncate to 30 chars, send (HOW)
3 new channel "push": write PushTransport; zero edits to OrderShipped or SecurityAlert
4 new kind "InvoiceDue": write one type; it works on all four transports at onceسناریوی واقعی: database/sql در Go (abstraction ای که صدا میزنید: DB، Tx، Rows) روی database/sql/driver (implementor ای که هر درایور میدهد: pgx، mysql، sqlite)؛ Logger در log/slog (front end) روی slog.Handler (back endهای text، JSON، OpenTelemetry)؛ API ِ Storage در Laravel روی adapterهای Flysystem؛ notificationهای Laravel روی کانالها؛ toolkit ِ ویجت UI روی سیستمهای پنجرهای پلتفرمها (مثال خود GoF)؛ یک گزارش (abstraction) روی rendererها (PDF، CSV، HTML).
Go:
// Bridge: two hierarchies that vary independently. The abstraction side
// (what kind of notification) holds a reference to the implementor side
// (how bytes travel). 2 kinds + 3 transports = 5 types, not 2 x 3 = 6.
package main
import (
"context"
"fmt"
"strings"
)
// Implementor: a transport knows how to deliver a rendered message.
type Transport interface {
Deliver(ctx context.Context, to string, subject, body string) error
}
type EmailTransport struct{}
func (EmailTransport) Deliver(_ context.Context, to, subject, body string) error {
fmt.Printf("[email to %s] %s: %s\n", to, subject, body)
return nil
}
type SMSTransport struct{ maxLen int }
func (s SMSTransport) Deliver(_ context.Context, to, _ string, body string) error {
if len(body) > s.maxLen {
body = body[:s.maxLen-3] + "..."
}
fmt.Printf("[sms to %s] %s\n", to, body)
return nil
}
type SlackTransport struct{ channel string }
func (s SlackTransport) Deliver(_ context.Context, _ string, subject, body string) error {
fmt.Printf("[slack %s] *%s* %s\n", s.channel, subject, body)
return nil
}
// Abstraction: a notification decides WHAT to say and WHEN, never HOW.
type Notification struct {
transport Transport // the bridge
}
// Refined abstractions.
type OrderShipped struct {
Notification
OrderID, Tracking string
}
func (n OrderShipped) Send(ctx context.Context, to string) error {
return n.transport.Deliver(ctx, to, "Order shipped",
fmt.Sprintf("Order %s is on its way, tracking %s", n.OrderID, n.Tracking))
}
type SecurityAlert struct {
Notification
Event string
}
// SecurityAlert adds behaviour of its own (urgency) without knowing transports.
func (n SecurityAlert) Send(ctx context.Context, to string) error {
return n.transport.Deliver(ctx, to, "SECURITY", strings.ToUpper(n.Event))
}
func main() {
ctx := context.Background()
sms := SMSTransport{maxLen: 30}
_ = OrderShipped{Notification{EmailTransport{}}, "A-17", "TRK9"}.Send(ctx, "ada@example.com")
_ = OrderShipped{Notification{sms}, "A-17", "TRK9"}.Send(ctx, "+98912")
_ = SecurityAlert{Notification{SlackTransport{"#sec"}}, "new login from unknown device"}.Send(ctx, "")
// Output:
// [email to ada@example.com] Order shipped: Order A-17 is on its way, tracking TRK9
// [sms to +98912] Order A-17 is on its way, t...
// [slack #sec] *SECURITY* NEW LOGIN FROM UNKNOWN DEVICE
}Laravel: notificationها شبیه Bridge هستند. یک notification تصمیم میگیرد چه بگوید و via() کانالها را در زمان اجرا انتخاب میکند؛ یک کانال سفارشی یک implementor جدید است. وابستگیای که نمیگذارد Bridge ِ خالص باشد این است که هر notification برای هر کانالی که پشتیبانی میکند متد toMail()، toSms()… لازم دارد.
<?php
// Bridge: notification kinds (abstraction) x delivery channels (implementor).
// Laravel's notification system is Bridge-like: a Notification says WHAT,
// a channel class says HOW, and via() connects them at runtime.
namespace App\Notifications;
use App\Notifications\Channels\SmsChannel;
use App\Notifications\Messages\SmsMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
final class OrderShipped extends Notification implements ShouldQueue
{
use Queueable;
public function __construct(public string $orderId, public string $tracking) {}
/** The bridge: pick implementors per recipient, at runtime. */
public function via(object $notifiable): array
{
return $notifiable->prefers_sms ? [SmsChannel::class] : ['mail', 'database'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Order shipped')
->line("Order {$this->orderId} is on its way, tracking {$this->tracking}.");
}
public function toSms(object $notifiable): SmsMessage
{
return new SmsMessage("Order {$this->orderId} shipped: {$this->tracking}");
}
/** @return array<string, string> */
public function toArray(object $notifiable): array
{
return ['order_id' => $this->orderId, 'tracking' => $this->tracking];
}
}
namespace App\Notifications\Messages;
final class SmsMessage
{
public function __construct(public string $text) {}
}
// A custom channel is one implementor; every notification that has toSms() can use it.
namespace App\Notifications\Channels;
use App\Notifications\Sms\SmsSender;
use Illuminate\Notifications\Notification;
final class SmsChannel
{
public function __construct(private SmsSender $sender) {} // the Adapter from Adapter.php
public function send(object $notifiable, Notification $notification): void
{
$message = $notification->toSms($notifiable);
$this->sender->send($notifiable->routeNotificationFor('sms'), $message->text);
}
}
// The coupling that makes it "Bridge-like" rather than a pure Bridge:
// each notification must know a toX() method per channel it supports, so adding
// a channel can require touching notifications. A pure Bridge has one implementor
// interface (e.g. deliver(to, subject, body)) that every abstraction uses unchanged.پیامدها: دو طرف جدا رشد میکنند و جدا تست میشوند؛ پیادهسازیها در زمان اجرا انتخابشدنیاند (config، tenant، feature flag)؛ تعداد کلاسها جمعی رشد میکند نه ضربی. هزینه: باید interface ِ Implementor را از اول درست پیدا کنید، و اگر خیلی کوچک باشد هر abstraction مجبور است دورش بزند (همان متدهای toX() بالا)؛ برای یک بُعد، سربار محض است.
کی استفاده نکنیم: وقتی فقط یک بُعد تغییر میکند (آن فقط یک interface با چند پیادهسازی است، یعنی Strategy یا DIP)؛ وقتی هنوز بُعد دوم را نمیشناسید (صبر کنید؛ وقتی گونهٔ دوم پیدا شد به Bridge refactor کنید).
Flyweight (سبکوزن) تکمیلی
به زبان ساده: وقتی تعداد بسیار زیادی شیء دارید که هر کدام همان دادهٔ سنگین را حمل میکنند، یک نسخهٔ مشترک از آن داده نگه دارید و به هر شیء فقط یک اشارهگر بهاضافهٔ دادهٔ کوچک و یکتای خودش بدهید. همان یک طرح نقشه برای 10,000 مهمان هتل.
بدفهمی رایج: «Flyweight یک cache است.» cache نتیجهها را نگه میدارد تا دوباره محاسبه نشوند؛ flyweight state ِ مشترک تغییرناپذیر را نگه میدارد تا حافظه تکثیر نشود. قاعدهٔ refactoring.guru صریح است: "Use the Flyweight pattern only when your program must support a huge number of objects which barely fit into available RAM."
تعریف (نیت GoF): "Use sharing to support large numbers of fine-grained objects efficiently." تمایز کلیدی: state ِ ذاتی (Intrinsic state) "is stored in the flyweight; it consists of information that's independent of the flyweight's context, thereby making it sharable"؛ state ِ بیرونی (Extrinsic state) "depends on and varies with the flyweight's context and therefore can't be shared"، پس کلاینت نگهش میدارد و پاسش میدهد.
مسئله: نقشهای با 100,000 marker که هر کدام یک آیکون 4 کیلوبایتی دارد: 390 مگابایت bitmap ِ یکسان. ویرایشگر متنی با یک شیء برای هر کاراکتر، هر کدام با مشخصات فونت. سرویسی که میلیونها ردیف دارد و هر کدام رشتهٔ تکراریای مثل "eu-west-1/orders/v2" دارد.
| شرکتکننده | نقش | در snippet |
|---|---|---|
| Flyweight | state ِ ذاتی را نگه میدارد؛ باید تغییرناپذیر باشد | MarkerStyle |
| FlyweightFactory | flyweightهای مشترک را میسازد و تحویل میدهد | StyleFactory.Get، MarkerStyleFactory::for، unique.Make |
| Context (کلاینت) | state ِ بیرونی + یک ارجاع به flyweight | Marker{Lat, Lng, Style} |
Loop i Factory.Get(kind) Heap
1 i = 0 "cafe" not in map → new MarkerStyle +4 KiB
2 i = 1 "atm" not in map → new MarkerStyle +4 KiB
3 i = 2.. found → return the same pointer +24 B per Marker (lat, lng, pointer)
4 100,000 markers: measured +2.3 MiB heap, vs ~390 MiB if each Marker copied its iconسناریوی واقعی: interning ِ رشتهها (unique.Make در Go، String.intern در Java، رشتههای interned در OPcache ِ PHP)؛ کش glyph و فونت در رندر متن؛ sprite و tile در بازیها؛ markerهای نقشه و styleهای نمودار؛ اشیای شبیه enum (enumهای PHP: "each case is backed by a singleton object")؛ اشیای پیکربندی مشترک و تغییرناپذیر که میلیونها موجودیت به آنها ارجاع میدهند؛ مقدارهای time.Location در Go که همهٔ time.Timeها شریکشان هستند.
Go: یک factory ِ دستنویس با map ِ محافظتشده با mutex، و package ِ unique ِ کتابخانهٔ استاندارد. بلاگ Go توضیح میدهد unique ورودیها را فقط تا وقتی handle وجود دارد نگه میدارد: "when the canonical entries are no longer being used, then the garbage collector is free to clean them up."
// Flyweight: share the intrinsic (context-free) part of many small objects
// and pass the extrinsic part in. Two Go forms: a hand-written factory with
// a map, and the standard library's unique package (Go 1.23+).
package main
import (
"fmt"
"runtime"
"sync"
"unique"
)
// Intrinsic state: identical for every map marker of the same kind.
type MarkerStyle struct {
Icon [4096]byte // pretend this is a decoded 4 KiB bitmap
Color string
Label string
}
// Flyweight factory: one shared *MarkerStyle per kind.
type StyleFactory struct {
mu sync.Mutex
styles map[string]*MarkerStyle
}
func (f *StyleFactory) Get(kind string) *MarkerStyle {
f.mu.Lock()
defer f.mu.Unlock()
if s, ok := f.styles[kind]; ok {
return s
}
s := &MarkerStyle{Color: map[string]string{"cafe": "brown", "atm": "green"}[kind], Label: kind}
f.styles[kind] = s
return s
}
// Context object: extrinsic state (position) + a pointer to the flyweight.
type Marker struct {
Lat, Lng float64
Style *MarkerStyle
}
func heapMB() float64 {
var m runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m)
return float64(m.HeapAlloc) / (1 << 20)
}
func main() {
f := &StyleFactory{styles: map[string]*MarkerStyle{}}
kinds := []string{"cafe", "atm"}
before := heapMB()
markers := make([]Marker, 100_000)
for i := range markers {
markers[i] = Marker{Lat: float64(i) / 1e3, Lng: 51.4, Style: f.Get(kinds[i%2])}
}
fmt.Printf("100k markers share %d styles, heap +%.1f MiB (without sharing: ~%d MiB of icons)\n",
len(f.styles), heapMB()-before, 100_000*4096>>20)
// unique.Make interns comparable values: equal values -> equal handles,
// and comparing handles is a pointer comparison.
a := unique.Make("eu-west-1/orders/v2")
b := unique.Make("eu-west-1/orders/" + "v2")
fmt.Println(a == b, a.Value())
runtime.KeepAlive(markers)
// Output:
// 100k markers share 2 styles, heap +2.3 MiB (without sharing: ~390 MiB of icons)
// true eu-west-1/orders/v2
}Laravel / PHP: caseهای enum بهعنوان flyweight، یک pool ِ استاتیک برای دادههای مشترک سنگینتر، و هشدار طول عمر که زیر Octane اهمیت پیدا میکند.
<?php
namespace App\Map;
// 1) Enum cases are shared singleton objects: a built-in flyweight.
enum MarkerKind: string
{
case Cafe = 'cafe';
case Atm = 'atm';
case Pharmacy = 'pharmacy';
// Intrinsic state lives on the case, computed, never copied per marker.
public function color(): string
{
return match ($this) {
self::Cafe => '#8B4513',
self::Atm => '#2E8B57',
self::Pharmacy => '#C0392B',
};
}
public function icon(): string
{
return "icons/{$this->value}.svg";
}
}
// 2) A hand-written flyweight factory for heavier intrinsic state.
final class MarkerStyle
{
public function __construct(
public readonly string $color,
public readonly string $svg, // e.g. 6 KB of SVG markup, loaded once
) {}
}
final class MarkerStyleFactory
{
/** @var array<string, MarkerStyle> */
private static array $pool = [];
public static function for(MarkerKind $kind): MarkerStyle
{
return self::$pool[$kind->value] ??= new MarkerStyle(
$kind->color(),
(string) file_get_contents(public_path($kind->icon())),
);
}
}
// Context object: extrinsic state (lat/lng) + a reference to the shared flyweight.
final class Marker
{
public function __construct(
public readonly float $lat,
public readonly float $lng,
public readonly MarkerStyle $style,
) {}
}
// 50,000 markers, 3 MarkerStyle objects:
// $markers = $places->map(fn ($p) => new Marker($p->lat, $p->lng, MarkerStyleFactory::for($p->kind)));
// MarkerKind::Cafe === MarkerKind::from('cafe'); // true: the same object
//
// Lifetime note: under PHP-FPM the static pool lives for one request; under
// Laravel Octane it lives for the whole worker, so only pool immutable data.پیامدها: صرفهجویی بزرگ در حافظه وقتی بخش مشترک بزرگ و تعداد اشیاء خیلی زیاد است؛ مقایسهٔ برابری به مقایسهٔ اشارهگر تبدیل میشود. هزینه: پیچیدگی کد (state دو تکه میشود)؛ flyweight باید تغییرناپذیر باشد، وگرنه یک تغییر در 100,000 جا ظاهر میشود؛ factory زیر همروندی قفل لازم دارد؛ «طول عمر» سؤال میشود (یک pool ِ استاتیک در Laravel Octane به اندازهٔ عمر worker زنده است).
کی استفاده نکنیم: وقتی هزاران شیء دارید نه میلیونها؛ وقتی بخش مشترک کوچک است (اشارهگر 8 بایت است؛ شریک کردن یک struct ِ 16 بایتی چیزی صرفهجویی نمیکند)؛ قبل از اینکه حافظه را اندازه گرفته باشید.
تشخیص wrapperها از هم
نمودار ساختار Adapter و Proxy و Decorator تقریباً یکی است: شیئی که یک interface را پیاده میکند و ارجاعی به شیء دیگر نگه میدارد. کل بخش بحث GoF به این دلیل وجود دارد که "the similarities belie the different intents". این جدول نسخهای است که باید نگه دارید.
| Adapter | Bridge | Decorator | Proxy | Facade | |
|---|---|---|---|---|---|
| نیت در یک خط | یک interface موجود را جور کن | دو بُعد را جدا کن | مسئولیت اضافه کن، قابل روی هم چیدن | دسترسی به یک subject را کنترل کن | یک زیرسیستم را ساده کن |
| interfaceی که کلاینت میبیند | Target (متفاوت از adaptee) | مال abstraction | همان component | همان subject | تازه، سطح بالاتر |
| میپوشاند | یک adaptee | یک implementor (با ارجاع) | یک component | یک subject | چند شیء |
| روی هم چیده میشود؟ | بهندرت | نه | بله، از اساس | بهندرت ("not designed for recursive composition"، GoF) | نه |
| چه کسی شیء پوشیده را میسازد | معمولاً صدازننده پاسش میدهد | موقع ساخت پیکربندی میشود | صدازننده، بعد میپوشاند | اغلب خود proxy (virtual proxy) | facade یا container |
| کی طراحی میشود | بعد از واقعه | قبل از رشد سلسلهمراتبها | هر وقت | هر وقت | هر وقت |
| مثال Go | http.HandlerFunc، adapter ِ SDK | database/sql × driver | bufio.Writer، middleware | httputil.ReverseProxy، sync.OnceValues | http.Get |
| مثال Laravel | storeهای cache، adapterهای Flysystem | Notification × channel | middleware، Container::extend | facadeهای Laravel، lazy proxyها | یک کلاس سرویس روی فراخوانیهای SDK |
| همزاد در مقیاس شبکه | anti-corruption layer، مترجم پروتکل | transport ِ قابلتعویض در یک کتابخانهٔ client | sidecar که mTLS و retry اضافه میکند | reverse proxy، CDN، sidecar | API gateway، BFF |
ترکیبهایی که خواهید دید. یک API gateway همزمان Facade است (یک ورودی، تجمیع) و Proxy (احراز هویت، cache، مسیریابی). یک anti-corruption layer یک Adapter (port شما را پیاده میکند) بهاضافهٔ یک Facade (یک فراخوانی به جای یک پروتکل) بهاضافهٔ یک translator است. یک sidecar یک Proxy است که اغلب مثل Decorator رفتار میکند (mTLS، retry، metrics اضافه میکند). یک caching decorator و یک caching proxy همان کدند؛ اگر یک لایه در پشتهای است که صدازننده میچیند اسمش را decorator بگذارید، اگر جانشین subject است و مالک دسترسی به آن، proxy.
نگاه هر زبان و فریمورک
| الگو | Go | Laravel / PHP | Java | .NET (C#) | TypeScript / Node | Python |
|---|---|---|---|---|---|---|
| Facade | تابعهای سطح package (http.Get) | کلاس سرویس؛ نه Illuminate\Support\Facades | Session Facade (Core J2EE Patterns) روی EJBها | کلاسهای سرویس | فایل index.ts ِ ماژول با API کوچک | API سطح ماژول (requests.get) |
| Adapter | interfaceهای ضمنی، HandlerFunc | Store، Flysystem، clientهای PSR-18 | InputStreamReader (بایت → کاراکتر) | StreamReader | کلاسهای wrapper روی SDKها | کلاسهای wrapper، io.TextIOWrapper |
| Composite | structهایی که []Interface دارند | rule objectها، درخت کامپوننت | Container در AWT/Swing | visual tree در WPF | درخت React/DOM | nodeهای ماژول ast |
| Proxy | ReverseProxy، OnceValues | facadeها، newLazyProxy، proxyهای Doctrine | java.lang.reflect.Proxy، proxyهای Spring AOP | DispatchProxy، proxyهای lazy loading در EF Core | شیء Proxy در ES | رد کردن با __getattr__ |
| Decorator | bufio، gzip، middleware | middleware، extend، middleware ِ Guzzle | BufferedInputStream، Collections.synchronizedList | BufferedStream، GZipStream | middleware در Express/Koa | middleware ِ WSGI؛ توابع با @functools.wraps |
| Bridge | database/sql × driver، slog × Handler | Notification × channel، Storage × adapter | DriverManager ِ JDBC × driver | providerهای ADO.NET | clientهای dialect در Knex | درایورهای DB-API |
| Flyweight | unique.Make | caseهای enum، رشتههای interned | کش Integer.valueOf، String.intern | string interning | رشتههای interned در V8 | کش اعداد کوچک، sys.intern |
سازوکار (Mechanics)
Go: رد کردن صریح، embedding و برآورده کردن interface حیاتی
یک wrapper در Go structی است که مقدار پوشیده را نگه میدارد و متدهای درست را دارد. دو سبک:
// Explicit forwarding: every method is written out. Safe; nothing leaks.
type countingWriter struct{ w io.Writer; n int64 }
func (c *countingWriter) Write(p []byte) (int, error) { n, err := c.w.Write(p); c.n += int64(n); return n, err }
// Embedding: the wrapper promotes every method of the embedded value and overrides some.
type statusRecorder struct {
http.ResponseWriter // Header() and Write() are promoted unchanged
status int
}
func (r *statusRecorder) WriteHeader(code int) { r.status = code; r.ResponseWriter.WriteHeader(code) }embedding کوتاهتر است، اما فقط متدهای type ِ ایستای مقدار embedشده را ارتقا میدهد. اگر یک http.ResponseWriter را embed کنید، wrapper متدهای Header و Write و WriteHeader را دارد و Flush و Hijack و ReadFrom را ندارد، حتی اگر مقدار پویا آنها را داشته باشد (ببینید Structs، methods و embedding و Interfaces). خطهایی مثل var _ Target = (*Adapter)(nil) اضافه کنید تا متد جاافتاده در زمان کامپایل گرفته شود.
interfaceهای اختیاری گمشده و Unwrap مهم
خیلی از APIهای Go با type assertion دنبال یک interface ِ اختیاری میگردند. decorator آن را پنهان میکند:
| interface ِ اختیاری | چه کسی دنبالش میگردد | وقتی wrapper پنهانش کند چه میشکند |
|---|---|---|
io.WriterTo / io.ReaderFrom | io.Copy: "If src implements WriterTo, the copy is implemented by calling src.WriteTo(dst). Otherwise, if dst implements ReaderFrom…" | مسیرهای سریع مثل sendfile از یک *os.File از دست میروند؛ کپی از طریق buffer انجام میشود |
http.Flusher | handlerهای streaming، SSE | w.(http.Flusher) شکست میخورد و server-sent events دیگر stream نمیشوند |
http.Hijacker | upgraderهای WebSocket | type assertion شکست میخورد و upgrade ِ WebSocket خطا برمیگرداند |
io.Closer | صدازنندههایی که بیرونیترین مقدار را میبندند | gzip.Writer flush نمیشود، یا فایل زیرین بسته نمیشود |
راهحل Go 1.20 تابع http.NewResponseController(w) است: "The ResponseWriter should be the original value passed to the Handler.ServeHTTP method, or have an Unwrap method returning the original ResponseWriter." پس هر decorator برای ResponseWriter که مینویسید باید func (r *statusRecorder) Unwrap() http.ResponseWriter داشته باشد، همانطور که snippet ِ decorator دارد.
ترتیب decoratorها و ترتیب بستنشان حیاتی
ترتیب پوشاندن همان ترتیب اجراست؛ بیرونیترین لایه اول اجرا میشود و آخر تمام میشود. برای writerها، flush از بیرون به داخل است: در bufio.NewWriter(gzip.NewWriter(file)) باید اول bufio.Writer را Flush کنید، بعد gzip.Writer را Close کنید (که footer ِ gzip را مینویسد)، بعد فایل را ببندید. اگر فقط درونیترین را ببندید یک آرشیو ناقص بدون هیچ خطایی میگیرید.
Chain A: Logging(Metrics(Retry(client))) Chain B: Retry(Logging(client))
1 one log line per logical call one log line per attempt
2 metrics: requests 1, failures 0 metrics (if inside): requests 3, failures 2
3 good for "what did the user experience" good for "how flaky is the dependency"
4 measured in the lab: A logs 1 line, B logs 3 lines (503, 503, 200)HTTP client ِ Laravel حلقهٔ retry() خود را دور کل پشتهٔ handlerهای Guzzle میگذارد (در سورس 13.x، PendingRequest::send هر فراخوانی sendRequest(...) را، که client ِ Guzzle و middlewareهایش را اجرا میکند، داخل helper ِ retry() میپیچد)، پس middleware ِ Guzzle که با withMiddleware ثبت شده برای هر تلاش یک بار اجرا میشود، مثل زنجیرهٔ B.
قرارداد RoundTripper و جای درست retry مهم
http.RoundTripper به نظر نقطهٔ بینقصی برای decorator ِ client است، و برای logging، tracing و هدر احراز هویت واقعاً هست. اما مستنداتش قاعده میگذارد: "RoundTrip should not attempt to interpret the response"، "RoundTrip should not modify the request, except for consuming and closing the Request's Body"، و "RoundTrip must always close the body, including on errors". retry ای که status code را بررسی میکند response را تفسیر میکند، و decorator ای که هدر اضافه میکند باید اول req.Clone(ctx) کند. به همین دلیل آزمایشگاه یک interface ِ کوچک Doer را تزئین میکند (Do(*http.Request) (*http.Response, error)، که *http.Client از قبل برآوردهاش میکند). یک decorator ِ retry همچنین باید: body را برای هر تلاش با Request.GetBody دوباره بسازد (که http.NewRequest برای typeهای رایج body خودکار تنظیم میکند) و اگر خالی است retry نکند، response ِ شکستخورده را قبل از تلاش بعدی تخلیه و بسته کند تا connection دوباره استفاده شود، روی ctx.Done() متوقف شود، و requestهای غیر idempotent را بدون idempotency key تکرار نکند (ببینید Timeouts، Retries و Jitter و API Idempotency). توجه کنید Transport خودش هم بعضی شکستها را retry میکند: "only retries a request upon encountering a network error if the connection has already been used successfully and if the request is idempotent"، و requestی با هدر Idempotency-Key را idempotent حساب میکند؛ decorator ِ شما روی این لایه مینشیند.
PHP: __call، __callStatic و container مهم
PHP میتواند proxyهای عمومی با متدهای جادویی بنویسد: __call($method, $args) هر فراخوانی نمونهای را رد میکند و __callStatic هر فراخوانی استاتیک را. Facade ِ Laravel از دومی استفاده میکند؛ Macroable از هر دو برای اضافه کردن متد در زمان اجرا استفاده میکند (و closure ِ macro را دوباره به کلاس هدف bind میکند: $macro->bindTo($this, static::class)، به همین دلیل self:: داخل یک macro به کلاس شما اشاره نمیکند). هزینهٔ رد کردن جادویی: بدون docblockهای @method نه تحلیل ایستا دارید نه تکمیل خودکار IDE، و هر فراخوانی از یک dispatch ِ پویا عبور میکند.
Container::extend($abstract, $closure) قلاب decorator در Laravel است. طبق سورس 13.x: اگر سرویس از قبل بهعنوان نمونهٔ shared resolve شده باشد، closure فوراً اعمال میشود و binding «rebound» میشود؛ وگرنه closure در $extenders[$abstract] صف میشود و هر بار که سرویس resolve میشود اعمال میگردد. چند extend به ترتیب ثبت روی هم چیده میشوند، پس آخری بیرونیترین لایه است.
lazy objectهای PHP 8.4 تکمیلی
PHP 8.4 virtual proxy را به یک قابلیت زبان تبدیل کرد. ReflectionClass::newLazyGhost() شیئی از کلاس واقعی میسازد که initializerش آن را درجا پر میکند؛ newLazyProxy() یک proxy میسازد که factoryاش یک نمونهٔ واقعی جدا برمیگرداند و بعد از آن دسترسی به propertyها به آن رد میشود. هر دو با اولین دسترسی به state ِ شیء فعال میشوند، نه موقع ساخت. هشدار دفترچهٔ PHP دربارهٔ proxyها: proxy و نمونهٔ واقعی دو شیء با هویت متفاوتاند، پس چک هویت (===) میتواند غافلگیرتان کند.
هویت، برابری و چک type مهم
GoF دربارهٔ Decorator: "a decorated component is not identical to the component itself. Hence you shouldn't rely on object identity when you use decorators." همین برای proxyها هم صادق است. در Go یک type switch روی *os.File وقتی فایل پوشیده شده شکست میخورد؛ errors.As از میان errorهای پوشیده فقط به این دلیل کار میکند که errorها Unwrap را پیاده میکنند. در PHP، instanceof EloquentCatalog روی caching proxy شکست میخورد. Flyweight حالت برعکس است: به هویت تکیه میکند (یک اشارهگر برای هر نوع، MarkerKind::Cafe === MarkerKind::from('cafe')).
کارایی: هزینهٔ wrap کردن، اندازهگیریشده تکمیلی
با benchmark ِ داخل snippetها اندازه گرفته شده (go test -bench . -benchmem ./bench، Go 1.27، Apple M5). عددها را مرتبهٔ بزرگی برای ماشین خودتان بدانید، نه ثابت.
| Benchmark | ns/op | B/op | allocs/op | چه چیزی را نشان میدهد |
|---|---|---|---|---|
| فراخوانی مستقیم متد | 0.24 | 0 | 0 | خط مبنا |
| فراخوانی از طریق interface | 0.25 | 0 | 0 | مثل مستقیم: کامپایلر فراخوانی را devirtualize کرد (-gcflags=-m چاپ میکند "devirtualizing p.Price to base") |
| پنج decorator ِ روی هم، یک بار ساختهشده | 3.56 | 0 | 0 | حدود 0.7 ns برای هر لایهٔ dispatch ِ interface |
| پنج decorator که در هر فراخوانی ساخته میشوند | 35.08 | 80 | 5 | هر &fee{...} به heap فرار میکند: زنجیره را یک بار، موقع شروع بسازید |
قاعدههایی که نتیجه میشوند: زنجیرهٔ decorator را یک بار بسازید (در main یا یک service provider)، نه برای هر request؛ در مسیرهای داغ از closureهای هر فراخوانی پرهیز کنید؛ یک decorator ِ بافردار (bufio) معمولاً خیلی بیشتر از هزینهٔ dispatchاش صرفهجویی میکند (syscall کمتر)؛ در PHP-FPM هر request کل container را از نو میسازد، پس زنجیرهٔ عمیق extend در هر request پرداخت میشود، در حالی که زیر Octane یک بار برای هر worker.
Go
نگاه Go
Go نه کلاس دارد نه وراثت، پس هر الگوی ساختاری شکل شیئیاش است: یک struct (یا یک type ِ تابعی) که یک مقدار interface نگه میدارد. سه قابلیت زبان بیشتر کار را انجام میدهند. interfaceهای ضمنی (Implicit interfaces) یعنی type ِ یک کتابخانهٔ بیرونی ممکن است همین حالا port شما را برآورده کند، پس خیلی از adapterها لازم نیستند. typeهای تابعی با متد (http.HandlerFunc، DoerFunc ِ آزمایشگاه) یک closure را به مقدار interface تبدیل میکنند و decoratorها را یکخطی میکنند. embedding رد کردن جزئی ارزان میدهد، با هشداری که در سازوکار آمد.
| الگو | نمونه در کتابخانهٔ استاندارد | چه چیزی را ببینید |
|---|---|---|
| Decorator | bufio.NewReader/Writer، gzip.NewReader/Writer، io.TeeReader، io.LimitReader، cipher.StreamReader | همان interface ورودی و خروجی؛ flush و close از بیرون به داخل |
| Decorator | http.StripPrefix، http.TimeoutHandler، http.MaxBytesHandler | middleware ِ استاندارد: func(Handler, …) Handler |
| Adapter | http.HandlerFunc، io.NopCloser، strings.NewReader، bytes.NewReader | یک تابع یا مقدار که با یک interface جور شده |
| Composite | io.MultiWriter، io.MultiReader، errors.Join | یک مقدار که جای چند مقدار با همان interface مینشیند |
| Proxy (remote) | httputil.ReverseProxy با Rewrite، SetURL، SetXForwarded، ModifyResponse | "an HTTP Handler that takes an incoming request and sends it to another server" |
| Proxy (virtual) | sync.Once، sync.OnceValue، sync.OnceValues | ساخت در اولین استفاده، دقیقاً یک بار، امن برای صدازنندههای همروند |
| Bridge | database/sql × database/sql/driver؛ log/slog.Logger × slog.Handler | API ِ جلو و پیادهسازیهای پشت مستقل تغییر میکنند |
| Flyweight | unique.Make / unique.Handle[T] | interning؛ handleهای برابر مثل اشارهگر مقایسه میشوند |
| Facade | http.Get، http.Post، os.ReadFile | یک فراخوانی روی یک client، یک transport، یک فایل و bufferش |
دو قاعدهٔ مخصوص Go. اول، portها را کوچک نگه دارید: adapter برای یک interface ِ دومتدی راحت نوشته و جعل میشود، اما adapter برای یک interface ِ بیستمتدی یک پروژه است (Interface Segregation). دوم، interface را جایی تعریف کنید که استفاده میشود، نه جایی که پیاده میشود، تا adapter به package ِ شما وابسته باشد نه برعکس (Dependency Inversion). صفحههای Go دربارهٔ io readers and writers و middlewares دو خانوادهٔ بزرگ decorator را عمیقتر باز میکنند.
Laravel
نگاه Laravel
Laravel از الگوهای ساختاری ساخته شده و بعضی اسمهایش با اسمهای GoF تصادم دارند. این نقشه است.
| قابلیت Laravel | الگوی GoF | شاهد (مستندات یا سورس Laravel 13) |
|---|---|---|
Illuminate\Support\Facades\* | Proxy (+ Service Locator)، نه Facade | "Laravel facades serve as "static proxies" to underlying classes in the service container" |
real-time facadeها (use Facades\App\…) | Proxy ِ ساختهشده در لحظه | "you may treat any class in your application as if it was a facade" |
| middleware ِ HTTP | Decorator + Chain of Responsibility | "a series of "layers" HTTP requests must pass through"؛ میتواند request را رد کند |
$this->app->extend() | ثبت Decorator | "you may run additional code to decorate or configure the service" |
storeهای cache، Cache::extend | Adapter (به Illuminate\Contracts\Cache\Store) | "we first need to implement the Illuminate\Contracts\Cache\Store contract" |
Storage + Flysystem، Storage::extend | Adapter، و Bridge (API ِ دیسک × adapter) | "simple drivers for working with local filesystems, SFTP, and Amazon S3… the API remains the same" |
withMiddleware، withRequestMiddleware، withResponseMiddleware، globalRequestMiddleware در HTTP client | Decorator (middleware ِ Guzzle) | "Since Laravel's HTTP client is powered by Guzzle, you may take advantage of Guzzle Middleware" |
Http::macro، Macroable | الگوی GoF نیست: اضافه کردن متد در زمان اجرا | Http::macro('github', …) در مستندات |
via() در notificationها + کانالها | شبیه Bridge | "write your own drivers to deliver notifications via other channels"؛ کانال سفارشی "a class that contains a send method" است |
| relationshipهای Eloquent (lazy) | Lazy Load (شبیه proxy) | "Dynamic relationship properties perform "lazy loading"" |
Model::preventLazyLoading() | محافظ در برابر هزینهٔ پنهان proxy | "instruct Laravel to always prevent the lazy loading of relationships" |
rule objectها (ValidationRule)، آرایهٔ ruleها | Composite (ruleی ساخته از ruleها) | validate(string $attribute, mixed $value, Closure $fail) |
| enumهای PHP 8.1 | Flyweight | "each case is backed by a singleton object of that name" (دفترچهٔ PHP) |
newLazyProxy / newLazyGhost در PHP 8.4 | Virtual proxy | "Ghost Objects and Virtual Proxies" (دفترچهٔ PHP) |
استانداردهای PSR این adapterها و decoratorها را بین فریمورکها قابل حمل میکنند: پیامهای PSR-7 تغییرناپذیرند (پس decorator یک کپی ِ تغییریافته برمیگرداند، $request->withHeader(...))، PSR-15 middleware و request handler ِ سمت سرور را تعریف میکند، و PSR-18 متد ClientInterface::sendRequest() را که هر adapter ِ HTTP client پیاده میکند. PSR-18 به نویسندگان decorator هشدار هم میدهد که requestی که client میفرستد "MAY be a different object from the one passed to ClientInterface::sendRequest()"، پس هرگز requestها را در طول زنجیرهٔ middleware با === مقایسه نکنید.
حل مسئلههای کلاسیک
| مسئله | الگو(ها) | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
| typeهای SDK ِ vendor همهجا | Adapter (+ ACL) | port ِ خودتان؛ یک adapter برای هر vendor | تعویض vendor، جعل در تست | ترجمه ممکن است جزئیات را گم کند |
| کد سراسری یکسان در هر فراخوانی client | Decorator | logging، metrics، retry، auth بهشکل لایه | یک کلاس برای هر دغدغه، هر ترتیبی | باگ ترتیب، stack trace ِ بلند |
| وابستگی کند یا راه دور | Proxy (caching، virtual) | wrapper ِ cache-aside، ساخت تنبل | بدون تغییر صدازننده | کهنگی داده، invalidation |
| queryهای N+1 | Proxy ِ خرابشده (lazy loading) | eager-load، preventLazyLoading | تعداد query ِ قابل پیشبینی | باید الگوی دسترسی را بدانید |
| انفجار کلاس (نوع × کانال) | Bridge | دو سلسلهمراتب + یک ارجاع | رشد جمعی | interface ِ Implementor باید درست باشد |
| دادهٔ درختی با چک type | Composite | یک interface برای برگ و گروه | کلاینت ساده | محدود کردن نوع فرزند سخت است |
| انفجار حافظه از تکرار | Flyweight | شریک کردن state ِ ذاتی تغییرناپذیر | صرفهجویی بزرگ RAM | state ِ دوتکه، قاعدهٔ تغییرناپذیری |
| controllerهایی که پنج سرویس را هماهنگ میکنند | Facade | یک کلاس use case | یک جا برای ترتیب و جبران | ممکن است god class شود |
قفل شدن به vendor و لایهٔ ضدفساد
یک adapter یک interface را ترجمه میکند. وقتی طرف مقابل مدل ِ دیگری دارد (اسمها، واحدها، وضعیتها و کدهای خطای دیگر)، به لایهٔ ضدفساد (Anti-corruption layer) نیاز دارید؛ توصیف Azure: "a facade or adapter layer between different subsystems that don't share the same semantics. This layer translates requests that one subsystem makes to the other subsystem." در کد سه بخش دارد: یک port که دامنهٔ شما مالکش است، یک translator که در هر دو جهت نگاشت میکند، و یک adapter/facade که port را با یک فراخوانی پیاده میکند. آزمایشگاه یکی میسازد. زمینهٔ راهبردی (conformist در برابر ACL در برابر open host) در Context Maps و الگوهای یکپارچهسازی است؛ داستان مهاجرت (ACL راهی است که یک strangler fig با سیستم قدیمی حرف میزند) صفحهٔ خودش را دارد.
-- The legacy side often shows up as a schema too. Map it in ONE place (a view or the translator),
-- never by letting domain code read legacy columns.
CREATE VIEW payments_v AS
SELECT txn_ref AS payment_id,
CAST(amt_str AS BIGINT) AS amount_minor, -- '000001500000' → 1500000
cur AS currency,
CASE rc WHEN '00' THEN 'approved'
WHEN '51' THEN 'declined_insufficient_funds'
WHEN '62' THEN 'declined_card_blocked'
ELSE 'unknown' END AS status
FROM legacy_pay_txn;دغدغههای سراسری بدون وراثت
برای دغدغههایی که روی هر فراخوانی یک interface اعمال میشوند (logging، metrics، tracing، retry، timeout، هدر auth، caching) از decorator استفاده کنید و قواعد کسبوکار را بیرون از آنها نگه دارید. زنجیره را در یک جا بسازید (main در Go، یک service provider در Laravel با extend، یک پشتهٔ Guzzle از طریق Http::macro). ترتیب را صریحاً در یک comment بنویسید؛ ترتیب بخشی از طراحی است (ببینید ترتیب decoratorها).
lazy loading و N+1
هر virtual proxy همین حالت شکست را دارد: صدازننده هزینه را نمیبیند، پس آن را در حلقه صدا میزند. برای Eloquent: با with() eager-load کنید، Model::preventLazyLoading() را بیرون از production روشن کنید و تعداد query را در تستها بپایید. برای Go: یک فراخوانی شبکه را پشت متدی که شبیه دسترسی به یک فیلد است پنهان نکنید؛ context.Context بگیرید تا هزینه در امضا دیده شود.
انفجار کلاس
وقتی اسمها شبیه PdfInvoiceReport، CsvInvoiceReport، PdfSalesReport، CsvSalesReport هستند، دو بُعد در یک سلسلهمراتب دارید. بُعد دوم را به یک interface (همان Implementor) استخراج کنید و با ارجاع نگهش دارید (Bridge). اگر واقعاً فقط یک بُعد تغییر میکند، یک interface ِ ساده با چند پیادهسازی (Strategy، DIP) کافی است.
انتخاب
| وضعیت | استفاده کنید | تکنیک اضافه | دلیل |
|---|---|---|---|
| SDK ِ یک vendor نباید نشت کند | Adapter پشت port ِ خودتان | contract test روی port | قابل تعویض، تستپذیر |
| سیستم دیگری با مدل متفاوت | Anti-corruption layer (Adapter + Facade + translator) | نگاشت خطاها به خطاهای دامنه؛ در یک ماژول | مدل شما را از مدل آنها محافظت میکند |
| controllerها یک جریان چندمرحلهای را تکرار میکنند | Facade (یک کلاس use case یا سرویس) | کوچک نگه دارید؛ یکی برای هر use case | یک جا برای ترتیب و جبران |
| logging/metrics/retry دور یک client | زنجیرهٔ Decorator | یک بار موقع شروع بسازید؛ ترتیب را مستند کنید | لایههای ترکیبپذیر و تستپذیر |
| شیء گران که بهندرت استفاده میشود | Virtual proxy | sync.OnceValues، newLazyProxy در PHP 8.4 | boot سریعتر |
| خواندنهای تکراری دادهٔ کند | Caching proxy | TTL + invalidation ِ صریح؛ Caching | query و فراخوانی کمتر |
| مجوز وابسته به یک شیء | Protection proxy، یا policy در لبه | Policy / Gate در Laravel | اعمال یکنواخت |
| فراخوانی سرویس دیگر | Remote proxy (stub ِ client، reverse proxy) | timeout، retry، circuit breaker بهشکل decorator | شفافیت مکانی، با احتیاط |
| درختی از چیزها با یک عملیات | Composite | Add به سبک ایمنی فقط روی composite | کلاینت یکنواخت |
| دو بُعد که هر دو رشد میکنند | Bridge | اول interface ِ implementor را طراحی کنید | رشد جمعی |
| میلیونها شیء مشابه | Flyweight | اول حافظه را اندازه بگیرید؛ unique.Make | RAM |
| میخواهید در سند طراحی به facadeهای Laravel «facade» بگویید | آنها را static proxy بنامید | در کد دامنه وابستگی را inject کنید | واژگان دقیق |
در معماری: از یک پروسه تا سیستم توزیعشده
هفت الگو با بزرگ شدن جعبهها شکلشان را حفظ میکنند؛ چیزی که عوض میشود این است که فلشها به فراخوانیهای شبکه تبدیل میشوند که میتوانند شکست بخورند، کند باشند یا تکرار شوند.
Monolith (مونولیت): یک پروسه، یک دیتابیس
چطور ظاهر میشود: کلاسها و تابعها. Facadeها کلاسهای سرویس یا use case هستند؛ adapterها SDKهای vendor را میپوشانند؛ decoratorها middleware و extend هستند؛ proxyها repositoryهای کشدار و سرویسهای lazy؛ compositeها منو، rule و درخت کامپوننت.
سادهترین استفادهٔ درست: همهچیز را در یک composition root سیمکشی کنید (main در Go، service providerها در Laravel) تا ساختار در یک فایل دیده شود؛ port را type-hint کنید، نه vendor را.
مثال (ساده): وبلاگی که ایمیل را از طریق MailSender میفرستد، که با یک adapter دور SDK ِ ارائهدهنده پیاده شده و با extend یک decorator ِ logging گرفته.
مثال (پیچیده): فروشگاهی که checkout در آن CheckoutFacade::placeOrder را صدا میزند، که از Inventory استفاده میکند و یک port ِ PaymentGateway که با LegacyPayGateway (همان ACL) پیاده شده و در decoratorهای logging و metrics پیچیده شده، در حالی که کاتالوگ پشت یک caching proxy نشسته.
Modular monolith: ماژولها، مرزها، یک واحد deploy
چطور ظاهر میشود: هر ماژول یک facade (API عمومیاش) دارد و بقیه را پنهان میکند. ماژولهای دیگر فقط facade را صدا میزنند؛ این facade بهعنوان مرز است، نه فقط یک راحتی. فراخوانیهای بین ماژول جایی است که وقتی دو ماژول مدلهای متفاوت دارند adapter میگذارید، تا واژگان یک ماژول به دیگری نشت نکند. ببینید Modular Monolith.
billing module catalog module (public facade only)
1 Billing\InvoiceTotals ─────────────▶ Catalog\CatalogApi::priceOf($sku) (facade)
2 internal: PriceRepository, Discounts, Currency (hidden)
3 architecture test: billing may import Catalog\CatalogApi, never Catalog\Internal\*Microservices (میکروسرویس): الگوها با شبکه در وسط
API gateway = Facade + Proxy. یک نقطهٔ ورود واحد برای کلاینتها (Facade)، با مسیریابی و برونسپاری auth و TLS و rate limit و caching (Proxy)؛ Azure از "Gateway routing"، "Gateway aggregation" و "Gateway offloading" نام میبرد. تجمیع بخش facade است؛ مسیریابی و برونسپاری بخش proxy. جزئیات در API Gateway، BFF و Service Mesh.
Anti-corruption layer = Adapter + Facade. بین سرویس شما و یک سیستم قدیمی یا شخص ثالث با مدل متفاوت. میتواند ماژولی داخل سرویس شما باشد یا سرویس جداگانه؛ Azure یادآوری میکند که "adds latency to calls between the two systems".
Sidecar = یک Proxy ِ خارج از پروسه (که اغلب مثل Decorator رفتار میکند). Envoy یا proxy ِ یک mesh کنار هر نمونه mTLS، retry، timeout و metrics اضافه میکند بدون تغییر کد. برای اپ همان interface است (هنوز یک فراخوانی HTTP میزند)، با رفتار بیشتر در مسیر. ببینید Service Mesh و الگوی Sidecar.
decoratorهای سمت client. retry با jitter، timeout، circuit breaker و bulkhead هر client ِ خروجی را میپوشانند. آنها را در یک زنجیرهٔ decorator ِ یکبارهساخته بگذارید؛ تصمیم بگیرید metrics داخل retry باشد یا بیرونش؛ هرگز فراخوانی غیر idempotent را بدون idempotency key تکرار نکنید. ببینید Timeouts، Retries و Jitter و Circuit Breaker.
Client app ──▶ API gateway (facade: aggregate /checkout; proxy: JWT check, rate limit)
1 ├──▶ orders-svc (sidecar proxy: mTLS, retry 2x on 503)
2 └──▶ payments-svc
3 client: Logging(Metrics(Breaker(Retry(http.Client))))
4 ──▶ ACL (adapter + translator) ──▶ legacy switch "RC=51" → ErrInsufficientFundsدادههای توزیعشده: cache، CDN و remote proxy
caching proxy در هر لایه: mapهای درونپروسه، Redis (cache-aside)، cacheهای HTTP و CDNها (reverse proxyهایی که cache میکنند). هر کدام proxy ای است که تازگی داده را با تأخیر معامله میکند؛ بخش سخت invalidation و stampede است (Caching، CDNs). remote proxyها فاصله را پنهان میکنند، و فاصله همان جایی است که مغالطههای محاسبات توزیعشده زندگی میکنند: شبکه قابلاعتماد نیست، تأخیر صفر نیست. یک remote proxy باید شکست را دیدنی کند (error، context.Context، timeout)، نه اینکه وانمود کند یک شیء محلی است. Flyweight بین پروسهها به یک سرویس دادهٔ مرجع مشترک یا یک asset روی CDN تبدیل میشود: یک نسخه، ارجاع با ID.
مسیر مقیاسپذیری: 1×، 10×، 100×
| مقیاس | ساختار | عمل الگوهای ساختاری |
|---|---|---|
| 1× (یک اپ) | Monolith | adapter برای vendorها، چند facade، middleware؛ یک composition root |
| 10× (چند تیم، یک repo) | Modular monolith | facade ِ ماژول بهعنوان مرز؛ ACL بین ماژولهایی با مدل متفاوت؛ decorator ِ metrics روی هر port |
| 100× (سرویسهای زیاد) | سرویسها + gateway + mesh | gateway (facade + proxy)، sidecar، ACL در مرز سرویسها، زنجیرهٔ decorator ِ client با retry و breaker، CDN بهعنوان caching proxy |
آزمایشگاه
دو آزمایشگاه، هر کدام با Go (که آفلاین اجرا میشود) و Laravel (کد بازبینیشده). همهچیز از httptest استفاده میکند، پس شبکه لازم نیست.
آمادهسازی.
cd docs/snippets/design/structural-patterns/go
gofmt -l . && go vet ./... # no output from gofmt, vet cleanآزمایشگاه 1: زنجیرهٔ decorator ِ logging + metrics + retry دور یک HTTP client
// Lab: a decorator chain around an HTTP client.
// Doer is the small interface *http.Client already satisfies; every
// decorator implements it too, so they stack in any order.
package main
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync/atomic"
"time"
)
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
type DoerFunc func(*http.Request) (*http.Response, error)
func (f DoerFunc) Do(r *http.Request) (*http.Response, error) { return f(r) }
// Logging: one line per call that passes through it.
func Logging(log *slog.Logger, layer string) func(Doer) Doer {
return func(next Doer) Doer {
return DoerFunc(func(r *http.Request) (*http.Response, error) {
resp, err := next.Do(r)
status := 0
if resp != nil {
status = resp.StatusCode
}
log.Info(layer, "method", r.Method, "url", r.URL.Path, "status", status, "err", err)
return resp, err
})
}
}
// Metrics: counters a real system would export to Prometheus or OTel.
type Metrics struct{ Requests, Failures atomic.Int64 }
func (m *Metrics) Wrap(next Doer) Doer {
return DoerFunc(func(r *http.Request) (*http.Response, error) {
m.Requests.Add(1)
resp, err := next.Do(r)
if err != nil || resp.StatusCode >= 500 {
m.Failures.Add(1)
}
return resp, err
})
}
// Retry: replays idempotent requests on transport errors, 502, 503 and 504.
func Retry(attempts int, base time.Duration) func(Doer) Doer {
return func(next Doer) Doer {
return DoerFunc(func(r *http.Request) (*http.Response, error) {
if r.Method != http.MethodGet && r.Header.Get("Idempotency-Key") == "" {
return next.Do(r) // never blindly replay a non-idempotent call
}
if r.Body != nil && r.Body != http.NoBody && r.GetBody == nil {
return next.Do(r) // body cannot be replayed: one attempt only
}
var lastErr error
for i := range attempts {
req := r.Clone(r.Context()) // a RoundTripper must not see a mutated request
if r.Body != nil && r.GetBody != nil {
body, err := r.GetBody() // fresh copy of the body for every attempt
if err != nil {
return nil, err
}
req.Body = body
}
resp, err := next.Do(req)
if err == nil && !retryable(resp.StatusCode) {
return resp, nil
}
if err == nil {
io.Copy(io.Discard, resp.Body) // drain so the connection is reused
resp.Body.Close()
lastErr = fmt.Errorf("status %d", resp.StatusCode)
} else {
lastErr = err
}
if i == attempts-1 {
break
}
select { // exponential backoff that honours cancellation
case <-time.After(base << i):
case <-r.Context().Done():
return nil, r.Context().Err()
}
}
return nil, fmt.Errorf("after %d attempts: %w", attempts, lastErr)
})
}
}
func retryable(code int) bool {
return code == http.StatusBadGateway || code == http.StatusServiceUnavailable || code == http.StatusGatewayTimeout
}
// Chain applies the first decorator outermost.
func Chain(d Doer, ds ...func(Doer) Doer) Doer {
for i := len(ds) - 1; i >= 0; i-- {
d = ds[i](d)
}
return d
}
func main() {
var hits atomic.Int64
flaky := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hits.Add(1)%3 != 0 { // fails twice, then succeeds
http.Error(w, "busy", http.StatusServiceUnavailable)
return
}
fmt.Fprint(w, "paid")
}))
defer flaky.Close()
log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}))
base := &http.Client{Timeout: 2 * time.Second}
m := &Metrics{}
// A: logging and metrics OUTSIDE retry: one log line per logical call.
outer := Chain(base, Logging(log, "outer"), m.Wrap, Retry(3, 10*time.Millisecond))
// B: logging INSIDE retry: one log line per attempt.
inner := Chain(base, Retry(3, 10*time.Millisecond), Logging(log, "attempt"))
for _, c := range []Doer{outer, inner} {
req, _ := http.NewRequestWithContext(context.Background(), "GET", flaky.URL+"/charge", nil)
resp, err := c.Do(req)
if err != nil {
fmt.Println("error:", err)
continue
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Println("body:", strings.TrimSpace(string(b)))
}
fmt.Println("metrics (chain A): requests", m.Requests.Load(), "failures", m.Failures.Load())
// Cancellation wins over retry.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
defer cancel()
down := Chain(DoerFunc(func(*http.Request) (*http.Response, error) {
return nil, errors.New("connection refused")
}), Retry(5, 50*time.Millisecond))
req, _ := http.NewRequestWithContext(ctx, "GET", "http://payments.internal/charge", nil)
_, err := down.Do(req)
fmt.Println("with deadline:", err)
// Output:
// level=INFO msg=outer method=GET url=/charge status=200 err=<nil>
// body: paid
// level=INFO msg=attempt method=GET url=/charge status=503 err=<nil>
// level=INFO msg=attempt method=GET url=/charge status=503 err=<nil>
// level=INFO msg=attempt method=GET url=/charge status=200 err=<nil>
// body: paid
// metrics (chain A): requests 1 failures 0
// with deadline: context deadline exceeded
}اجرا کنید.
go run ./lab/httpclient. خروجی مورد انتظار (attribute ِ زمان برای خروجی پایدار حذف شده):textlevel=INFO msg=outer method=GET url=/charge status=200 err=<nil> body: paid level=INFO msg=attempt method=GET url=/charge status=503 err=<nil> level=INFO msg=attempt method=GET url=/charge status=503 err=<nil> level=INFO msg=attempt method=GET url=/charge status=200 err=<nil> body: paid metrics (chain A): requests 1 failures 0 with deadline: context deadline exceededتفاوت را توضیح دهید. زنجیرهٔ A برای هر فراخوانی منطقی یک بار log میکند چون logging بیرون از retry است؛ زنجیرهٔ B هر تلاش را log میکند. metrics در زنجیرهٔ A صفر شکست گزارش میکند با اینکه سرور دو بار شکست خورد: retry آنها را پنهان کرد.
m.Wrapرا داخلRetryببرید و انتظارrequests 3 failures 2را داشته باشید.body را بشکنید. request را به
POSTبا هدرIdempotency-Keyو body ِstrings.NewReader("amount=100")تغییر دهید و body را روی سرور چاپ کنید: هر سه تلاش باamount=100میرسند، چونhttp.NewRequestمقدارGetBodyرا تنظیم کرده و هم decorator ِ ما و همTransportبا آن body را از اول میخوانند. حالا body را بهشکلio.MultiReader(strings.NewReader("amount=100"))بپیچید، typeی کهNewRequestنمیشناسد، پسGetBodyخالی (nil) است. نگهبانGetBody == nilرا ازRetryپاک کنید و اجرا کنید: اندازهگیریشده، سرور اولamount=100و بعد""و بعد""میگیرد و فراخوانی با یک شارژ خالی «موفق» میشود. نگهبان را برگردانید: decorator حالا فقط یک تلاش میکند و همان 503 را برمیگرداند.تخلیه را حذف کنید.
io.Copy(io.Discard, resp.Body)را پاک کنید و connectionهای جدید را روی سرور تست بشمارید (httptest.NewUnstartedServer، تنظیمConfig.ConnState، بعدStart()). مستنداتnet/httpهشدار میدهد bodyی که "read to EOF and closed" نشده یعنی Transport "may not be able to re-use a persistent TCP connection". در اجرای ما (Go 1.27، localhost، body ِ خطای 5 بایتی و 64 KiB) شمارش در هر دو حالت 1 ماند، پس تخلیه را یک بیمهٔ ارزان بدانید که این آزمایشگاه اثرش را نشان نمیدهد.نسخهٔ Laravel. macro ِ snippet ِ پایین را ثبت کنید و تست Pest ِ commentشده را اجرا کنید:
Http::assertSentCount(3)و سه خط log ِpayments.http، چونretry()ِ Laravel کل پشتهٔ Guzzle را میپوشاند (زنجیرهٔ B).
<?php
// Lab: logging + metrics + retry around Laravel's HTTP client (Guzzle underneath).
namespace App\Providers;
use GuzzleHttp\Promise\Create;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;
final class PaymentsHttpServiceProvider extends ServiceProvider
{
/** In-process counters; export them to Prometheus/OTel in a real app. */
public static array $metrics = ['requests' => 0, 'failures' => 0];
public function boot(): void
{
// Build the decorators here: a macro closure is re-bound to the Http factory,
// so self:: inside it would no longer point at this provider.
$metrics = self::metrics();
$logging = self::logging();
// A macro gives the decorated client a name: Http::payments()->post(...).
Http::macro('payments', function () use ($metrics, $logging): PendingRequest {
return Http::baseUrl(config('services.payments.url'))
->timeout(3)
->acceptJson()
// Decorator 1: metrics (a full Guzzle middleware: handler -> handler).
->withMiddleware($metrics)
// Decorator 2: logging with duration.
->withMiddleware($logging)
// Decorator 3: a request-only decorator.
->withRequestMiddleware(fn (RequestInterface $r) => $r->withHeader('X-Client', 'shop/1.0'))
// Retry: Laravel loops around the WHOLE Guzzle stack, so the middleware
// above runs once per attempt (like chain B in the Go lab).
->retry(
3,
fn (int $attempt) => 100 * (2 ** ($attempt - 1)), // 100, 200, 400 ms
fn (Throwable $e, PendingRequest $request, ?string $method) =>
($method === 'GET' || isset($request->getOptions()['headers']['Idempotency-Key']))
&& ($e instanceof ConnectionException
|| ($e instanceof RequestException && in_array($e->response->status(), [502, 503, 504], true))),
);
});
}
private static function metrics(): callable
{
return fn (callable $handler) => function (RequestInterface $request, array $options) use ($handler) {
self::$metrics['requests']++;
return $handler($request, $options)->then(
function (ResponseInterface $response) {
if ($response->getStatusCode() >= 500) {
self::$metrics['failures']++;
}
return $response;
},
function ($reason) {
self::$metrics['failures']++;
return Create::rejectionFor($reason);
},
);
};
}
private static function logging(): callable
{
return fn (callable $handler) => function (RequestInterface $request, array $options) use ($handler) {
$start = hrtime(true);
return $handler($request, $options)->then(function (ResponseInterface $response) use ($request, $start) {
Log::info('payments.http', [
'method' => $request->getMethod(),
'path' => $request->getUri()->getPath(),
'status' => $response->getStatusCode(),
'ms' => intdiv(hrtime(true) - $start, 1_000_000),
]);
return $response;
});
};
}
}
// Test it without a network (tests/Feature/PaymentsClientTest.php):
//
// Http::fakeSequence('payments.test/*')
// ->pushStatus(503)->pushStatus(503)->push(['status' => 'paid'], 200);
// config(['services.payments.url' => 'https://payments.test']);
//
// $response = Http::payments()->get('/charges/42');
//
// expect($response->json('status'))->toBe('paid');
// Http::assertSentCount(3); // 2 retries + 1 success
// // Log has 3 "payments.http" lines: logging sits INSIDE the retry loop.آزمایشگاه 2: لایهٔ ضدفساد برای یک API ِ پرداخت قدیمی
// Lab: an anti-corruption layer (ACL) in front of a legacy payment API.
// Inside: our domain model (Money, ChargeResult, domain errors).
// Outside: a legacy gateway that speaks form posts, rial strings and
// two-digit response codes. The ACL is a facade (one call) built from an
// adapter (implements our port) and a translator (maps both models).
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"time"
)
// ===== our domain (no legacy words allowed in here) =====
type Money struct {
Minor int64 // smallest unit: cents, or rials for IRR
Currency string // ISO 4217
}
type ChargeResult struct {
PaymentID string
Approved bool
}
var (
ErrInsufficientFunds = errors.New("payment: insufficient funds")
ErrCardBlocked = errors.New("payment: card blocked")
ErrProviderDown = errors.New("payment: provider unavailable")
)
// Port: the interface our checkout depends on.
type PaymentGateway interface {
Charge(ctx context.Context, orderID string, amount Money) (ChargeResult, error)
}
// ===== the ACL =====
type LegacyPayACL struct {
baseURL string
merchantID string
http *http.Client
}
var _ PaymentGateway = (*LegacyPayACL)(nil)
// Translator, outbound: domain -> legacy wire format.
func toLegacy(merchant, orderID string, m Money) url.Values {
return url.Values{
"MERCHANT_ID": {merchant},
"AMT": {fmt.Sprintf("%012d", m.Minor)}, // zero-padded, 12 digits
"CUR": {m.Currency},
"REF": {strings.ToUpper(orderID)},
}
}
// Translator, inbound: legacy codes -> domain results and errors.
var legacyCodes = map[string]error{
"00": nil,
"51": ErrInsufficientFunds,
"62": ErrCardBlocked,
"91": ErrProviderDown,
}
func fromLegacy(body string) (ChargeResult, error) {
kv := map[string]string{}
for _, part := range strings.Split(strings.TrimSpace(body), ";") {
if k, v, ok := strings.Cut(part, "="); ok {
kv[k] = v
}
}
domainErr, known := legacyCodes[kv["RC"]]
if !known {
return ChargeResult{}, fmt.Errorf("payment: unknown legacy code %q", kv["RC"])
}
if domainErr != nil {
return ChargeResult{}, domainErr
}
return ChargeResult{PaymentID: "pay_" + kv["TXN"], Approved: true}, nil
}
func (a *LegacyPayACL) Charge(ctx context.Context, orderID string, amount Money) (ChargeResult, error) {
form := toLegacy(a.merchantID, orderID, amount)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.baseURL+"/cgi-bin/pay.exe",
strings.NewReader(form.Encode()))
if err != nil {
return ChargeResult{}, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := a.http.Do(req)
if err != nil {
return ChargeResult{}, fmt.Errorf("%w: %v", ErrProviderDown, err)
}
defer resp.Body.Close()
b, err := io.ReadAll(io.LimitReader(resp.Body, 4<<10)) // never trust legacy sizes
if err != nil {
return ChargeResult{}, err
}
return fromLegacy(string(b))
}
// ===== a fake legacy system for the lab =====
func legacyServer() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
amt, _ := strconv.ParseInt(r.PostForm.Get("AMT"), 10, 64)
switch {
case amt > 5_000_000:
fmt.Fprint(w, "RC=51;MSG=INSUFF FUNDS;TXN=0")
case r.PostForm.Get("REF") == "ORD-BLOCKED":
fmt.Fprint(w, "RC=62;MSG=RESTRICTED CARD;TXN=0")
default:
fmt.Fprintf(w, "RC=00;MSG=APPROVED;TXN=%s", r.PostForm.Get("REF"))
}
}))
}
func main() {
srv := legacyServer()
defer srv.Close()
var gw PaymentGateway = &LegacyPayACL{baseURL: srv.URL, merchantID: "M-001",
http: &http.Client{Timeout: 3 * time.Second}}
ctx := context.Background()
for _, tc := range []struct {
order string
minor int64
}{{"ord-1", 1_500_000}, {"ord-2", 9_000_000}, {"ord-blocked", 10}} {
res, err := gw.Charge(ctx, tc.order, Money{tc.minor, "IRR"})
switch {
case errors.Is(err, ErrInsufficientFunds):
fmt.Println(tc.order, "-> ask the customer for another card")
case err != nil:
fmt.Println(tc.order, "->", err)
default:
fmt.Println(tc.order, "->", res.PaymentID, res.Approved)
}
}
if _, err := fromLegacy("RC=05;MSG=DO NOT HONOR"); err != nil {
log.Println(err)
}
// Output:
// ord-1 -> pay_ORD-1 true
// ord-2 -> ask the customer for another card
// ord-blocked -> payment: card blocked
// <date> payment: unknown legacy code "05"
}اجرا کنید.
go run ./lab/acl. انتظار:textord-1 -> pay_ORD-1 true ord-2 -> ask the customer for another card ord-blocked -> payment: card blocked <date> <time> payment: unknown legacy code "05"مرز را پیدا کنید.
grep -n "RC\|AMT\|MERCHANT" lab/acl/main.go: همهٔ واژههای قدیمی داخل بخش ACL هستند؛main(همان «checkout») فقط ازMoney،ChargeResultوErrInsufficientFundsاستفاده میکند.یک کد اضافه کنید. سوییچ کد
RC=05(«do not honor») را اضافه میکند. آن را بهlegacyCodesبا یکErrDeclinedِ جدید اضافه کنید؛ هیچ صدازنندهای تغییر نمیکند.ارائهدهنده را عوض کنید. یک
StripeLikeACLبا همان port ِPaymentGatewayبنویسید؛mainفقط یک خط سازنده را عوض میکند.ACL را تزئین کنید.
gwرا در یک decorator ِ logging به سبک آزمایشگاه 1 بپیچید (PaymentGatewayورودی،PaymentGatewayخروجی). انتظار: ACL حالا Adapter + Facade ِ تزئینشده است: سه الگو، یک محل فراخوانی.نسخهٔ Laravel.
PaymentGatewayPortرا بهLegacyPayGatewaybind کنید و تست commentشده را باHttp::fakeاجرا کنید.
<?php
// Lab: an anti-corruption layer for a legacy payment API.
// Domain side: Money, ChargeResult, domain exceptions. Legacy side: form posts,
// zero-padded amounts, two-digit response codes. Only this namespace knows both.
namespace App\Payments;
final readonly class Money
{
public function __construct(public int $minor, public string $currency) {}
}
final readonly class ChargeResult
{
public function __construct(public string $paymentId, public bool $approved) {}
}
class PaymentDeclined extends \DomainException {}
final class InsufficientFunds extends PaymentDeclined {}
final class CardBlocked extends PaymentDeclined {}
final class ProviderUnavailable extends \RuntimeException {}
interface PaymentGatewayPort
{
public function charge(string $orderId, Money $amount): ChargeResult;
}
namespace App\Payments\LegacyPay;
use App\Payments\CardBlocked;
use App\Payments\ChargeResult;
use App\Payments\InsufficientFunds;
use App\Payments\Money;
use App\Payments\PaymentGatewayPort;
use App\Payments\ProviderUnavailable;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use UnexpectedValueException;
/** Translator: the only place that knows the legacy vocabulary. */
final class LegacyPayTranslator
{
/** @return array<string, string> */
public function toLegacy(string $merchantId, string $orderId, Money $m): array
{
return [
'MERCHANT_ID' => $merchantId,
'AMT' => str_pad((string) $m->minor, 12, '0', STR_PAD_LEFT),
'CUR' => $m->currency,
'REF' => strtoupper($orderId),
];
}
public function fromLegacy(string $body): ChargeResult
{
parse_str(str_replace(';', '&', trim($body)), $kv);
return match ($kv['RC'] ?? null) {
'00' => new ChargeResult('pay_'.$kv['TXN'], true),
'51' => throw new InsufficientFunds,
'62' => throw new CardBlocked,
'91' => throw new ProviderUnavailable('legacy switch down'),
default => throw new UnexpectedValueException('unknown legacy code '.($kv['RC'] ?? 'none')),
};
}
}
/** Adapter + facade: implements our port with one call. */
final class LegacyPayGateway implements PaymentGatewayPort
{
public function __construct(
private LegacyPayTranslator $translator,
private string $baseUrl,
private string $merchantId,
) {}
public function charge(string $orderId, Money $amount): ChargeResult
{
try {
$response = Http::asForm()
->timeout(5)
->post($this->baseUrl.'/cgi-bin/pay.exe', $this->translator->toLegacy($this->merchantId, $orderId, $amount));
} catch (ConnectionException $e) {
throw new ProviderUnavailable($e->getMessage(), previous: $e);
}
return $this->translator->fromLegacy($response->body());
}
}
// Wiring (a service provider): the rest of the app sees only PaymentGatewayPort.
// $this->app->singleton(PaymentGatewayPort::class, fn () => new LegacyPayGateway(
// new LegacyPayTranslator, config('services.legacypay.url'), config('services.legacypay.merchant'),
// ));
//
// Test (no network):
// Http::fake(['*/cgi-bin/pay.exe' => Http::response('RC=51;MSG=INSUFF FUNDS;TXN=0')]);
// expect(fn () => app(PaymentGatewayPort::class)->charge('ord-2', new Money(9_000_000, 'IRR')))
// ->toThrow(InsufficientFunds::class);آزمایشگاه 3 (اختیاری): wrap کردن را اندازه بگیرید
go test -bench . -benchmem ./bench
# BenchmarkDirect-10 1000000000 0.2434 ns/op 0 B/op 0 allocs/op
# BenchmarkInterface-10 1000000000 0.2539 ns/op 0 B/op 0 allocs/op
# BenchmarkChain5-10 334184730 3.560 ns/op 0 B/op 0 allocs/op
# BenchmarkBuildChainPerCall-10 36539690 35.08 ns/op 80 B/op 5 allocs/op// Package bench measures what wrapping costs in Go: a direct call, a call
// through an interface, and a call through a chain of decorators.
// Run: go test -bench . -benchmem ./bench
package bench
import "testing"
type Pricer interface{ Price(qty int) int }
type base struct{ unit int }
func (b base) Price(q int) int { return b.unit * q }
// decorator: same interface, adds one responsibility (here: a tiny fee).
type fee struct{ next Pricer }
func (f fee) Price(q int) int { return f.next.Price(q) + 1 }
var sink int
func BenchmarkDirect(b *testing.B) {
p := base{unit: 3}
for i := range b.N {
sink = p.Price(i)
}
}
func BenchmarkInterface(b *testing.B) {
var p Pricer = base{unit: 3}
for i := range b.N {
sink = p.Price(i)
}
}
func BenchmarkChain5(b *testing.B) {
var p Pricer = base{unit: 3}
for range 5 {
p = fee{next: p}
}
for i := range b.N {
sink = p.Price(i)
}
}
// Building the chain on every call (e.g. per request) allocates.
func BenchmarkBuildChainPerCall(b *testing.B) {
for i := range b.N {
var p Pricer = base{unit: 3}
for range 5 {
p = &fee{next: p}
}
sink = p.Price(i)
}
}بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| facadeهای Laravel همان Facadeِ GoF هستند | آنها «static proxy» به یک binding در container هستند؛ facadeِ GoF یک زیرسیستم را ساده میکند |
| facade باید زیرسیستم را کاملاً پنهان کند | GoF: مانع استفادهٔ مستقیم از کلاسهای زیرسیستم نمیشود؛ برای دیوار از internal/ یا قواعد ماژول استفاده کنید |
| Adapter، Decorator و Proxy یکیاند | ساختار یکسان، نیت متفاوت: عوض کردن interface / رفتار قابل روی هم چیدن / کنترل دسترسی |
| Bridge یک Adapter ِ شیک است | Adapter ناسازگاری را بعد از واقعه درست میکند؛ Bridge دو بُعد را از اول جدا میکند |
| هر wrapper دور یک API یک adapter است | فقط اگر interface ِ شما را پیاده کند و ترجمه کند؛ نشان دادن typeهای vendor تطبیق نیست |
| Composite یعنی «یک درخت» | یعنی برگ و ظرف یک interface دارند تا کلاینت شاخه نزند |
| ترتیب decoratorها مهم نیست | تعیین میکند چه چیزی log، retry، اندازهگیری و قطع میشود |
| caching proxy سرعت مجانی است | تأخیر را با کهنگی و مسئلهٔ invalidation میخرد |
| Flyweight یک cache است | state ِ ذاتی تغییرناپذیر را برای صرفهجویی حافظه شریک میکند؛ نتیجه ذخیره نمیکند |
| wrapperها در Go کندند | اندازهگیریشده: حدود 0.7 ns برای هر لایهٔ interface؛ allocation فقط اگر زنجیره را در هر فراخوانی بسازید |
| embedding همهچیز را رد میکند | فقط متدهای type ِ ایستا را؛ interfaceهای اختیاری مثل http.Flusher بدون Unwrap پنهان میشوند |
| lazy loading همیشه خوب است | هزینه را پنهان میکند؛ در حلقه N+1 میشود |
| ACL فقط یک adapter است | adapter + facade + translator است که از یک مدل کامل در مرز سرویس محافظت میکند |
| middleware فقط Chain of Responsibility است | از نظر ساختاری Decorator است؛ از نظر رفتاری میتواند مثل CoR قطع کند |
چکیده
| موضوع | به یاد بسپارید |
|---|---|
| Facade | interface ِ تازه و سادهتر روی چند کلاس؛ استفادهٔ مستقیم را ممنوع نمیکند |
| Adapter | interface ِ موجود به آنچه کلاینت انتظار دارد تبدیل میشود؛ شکل شیئی ارجح است |
| Composite | برگ و ظرف یک interface دارند؛ شفافیت در برابر ایمنی برای Add |
| Proxy | همان interface، کنترل دسترسی: remote، virtual، protection، smart reference، caching |
| Decorator | همان interface، یک مسئولیت اضافه، روی هم چیدنی؛ ترتیب مهم است |
| Bridge | abstraction × implementor، وصل با ارجاع؛ از اول طراحی میشود |
| Flyweight | state ِ ذاتی (مشترک، تغییرناپذیر) در برابر بیرونی (پاس دادهشده) |
| facadeهای Laravel | static proxy از طریق __callStatic + getFacadeAccessor؛ mock با shouldReceive |
Container::extend | قلاب decorator در Laravel؛ آخرین ثبت بیرونیترین است |
| decoratorهای Go | bufio، gzip، TeeReader، middleware؛ flush/close از بیرون به داخل |
Unwrap | به wrapperهای ResponseWriter متد Unwrap() بدهید تا ResponseController به Flush/Hijack برسد |
RoundTripper | آنجا response را تفسیر یا request را تغییر ندهید؛ retry روی یک Doer بالای client |
| decorator ِ retry | GetBody، تخلیه + بستن، رعایت ctx، فقط requestهای idempotent |
| Gateway / ACL / sidecar | Facade+Proxy / Adapter+Facade / Proxy ِ خارج از پروسه |
| کارایی | زنجیره را یک بار بسازید؛ wrap در هر فراخوانی allocation دارد |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — به گفتهٔ GoF چه چیزی Facade را از Adapter جدا میکند؟ حیاتی
پاسخ
پاسخ: facade "defines a new interface, whereas an adapter reuses an old interface": adapter یک interface ِ موجود (همانی که کلاینت انتظار دارد) را با یک کلاس ناسازگار جور میکند. ببینید تشخیص wrapperها از هم.
۲ — آیا Cache::get('k') در Laravel نمونهای از الگوی Facadeِ GoF است؟ پس چیست؟ حیاتی
پاسخ
پاسخ: نه. یک static proxy است: Facade::__callStatic binding ِ cache را از container resolve میکند و فراخوانی را رد میکند. به زبان GoF یک Proxy که از طریق Service Locator به آن میرسیم. ببینید facadeهای Laravel، static proxy هستند.
۳ — http.ResponseWriter را برای ثبت status code پوشاندهاید و server-sent events دیگر stream نمیشوند. چرا، و راهحل چیست؟ مهم
پاسخ
پاسخ: wrapper، interface ِ اختیاری http.Flusher ِ writer ِ اصلی را پنهان میکند. Unwrap() http.ResponseWriter اضافه کنید و از http.NewResponseController(w).Flush() استفاده کنید، یا Flush را صریحاً رد کنید. ببینید interfaceهای اختیاری گمشده.
۴ — یک decorator ِ retry برای GET کار میکند، اما retryهای POST با بدنهٔ خالی به سرور میرسند. چه چیزی خراب است؟ مهم
پاسخ
پاسخ: تلاش اول body را مصرف کرد و چیزی نتوانست آن را از اول بخواند: Request.GetBody خالی بود (type ِ body را http.NewRequest نمیشناخت) یا decorator از آن استفاده نکرد. body را برای هر تلاش با GetBody دوباره بسازید و اگر خالی است retry نکنید. همچنین باید responseهای شکستخورده را تخلیه و بسته کند، ctx را رعایت کند و فقط requestهای idempotent را تکرار کند. ببینید قرارداد RoundTripper و آزمایشگاه 1.
۵ — اگر برای هر فراخوانی قابلمشاهده برای کاربر یک خط log بخواهید، decorator ِ logging نسبت به retry کجا میرود؟ و برای دیدن ناپایداری وابستگی؟ مهم
پاسخ
پاسخ: بیرون از retry برای یک خط در هر فراخوانی منطقی؛ داخل retry برای یک خط در هر تلاش. ببینید ترتیب decoratorها و آزمایشگاه 1.
۶ — چهار نوع proxy ِ GoF را با یک مثال امروزی برای هر کدام نام ببرید. تکمیلی
پاسخ
پاسخ: Remote (stub ِ gRPC، httputil.ReverseProxy)، virtual (sync.OnceValues، newLazyProxy در PHP 8.4)، protection (یک wrapper ِ مجوزدهی)، smart reference (شمارش ارجاع، caching، copy-on-write). ببینید Proxy.
۷ — سه نوع notification و چهار کانال: با زیرکلاسسازی چند کلاس، با Bridge چند تا؟ حیاتی
پاسخ
پاسخ: 3 × 4 = 12 با یک زیرکلاس برای هر ترکیب؛ 3 + 4 = 7 با Bridge. ببینید Bridge.
۸ — تفاوت state ِ ذاتی و بیرونی چیست و کدام باید تغییرناپذیر باشد؟ مهم
پاسخ
پاسخ: state ِ ذاتی مستقل از زمینه است و در flyweight ِ مشترک ذخیره میشود؛ باید تغییرناپذیر باشد. state ِ بیرونی به زمینه وابسته است و کلاینت نگهش میدارد و پاسش میدهد. ببینید Flyweight.
۹ — در Composite منظور GoF از «شفافیت در برابر ایمنی» چیست؟ تکمیلی
پاسخ
پاسخ: گذاشتن متدهای مدیریت فرزند روی Component شفافیت میدهد (رفتار یکنواخت) اما اجازه میدهد کلاینت روی برگ Add صدا بزند؛ گذاشتنشان فقط روی Composite ایمنی میدهد اما برگ و مرکب متفاوت میشوند. ببینید Composite.
۱۰ — یک API gateway، یک anti-corruption layer و یک sidecar از کدام دو یا سه الگو ساخته شدهاند؟ مهم
پاسخ
پاسخ: API gateway: Facade + Proxy. ACL: Adapter + Facade (+ یک translator). Sidecar: یک Proxy ِ خارج از پروسه که اغلب مثل Decorator رفتار میکند. ببینید میکروسرویسها.
۱۱ — چرا lazy loading ِ Eloquent در یک حلقه خطرناک است و Laravel در برابرش چه میدهد؟ حیاتی
پاسخ
پاسخ: هر اولین دسترسی یک query اجرا میکند، پس حلقه روی N model، N+1 query اجرا میکند. با with() eager-load کنید و Model::preventLazyLoading() را بیرون از production روشن کنید. ببینید Proxy و lazy loading و N+1.
۱۲ — ساختن یک زنجیرهٔ decorator ِ پنجلایه در هر فراخوانی در Go، در مقایسه با یک بار ساختنش، چه هزینهای دارد؟ مهم
پاسخ
پاسخ: در benchmark ِ ما حدود 35 ns، 80 B و 5 allocation در هر فراخوانی، در برابر حدود 3.6 ns و صفر allocation وقتی زنجیره یک بار ساخته شود. ببینید کارایی.
واژهنامه
| اصطلاح | معنی |
|---|---|
| الگوی ساختاری (Structural pattern) | خانوادهٔ GoF دربارهٔ ترکیب کلاسها و اشیاء به ساختارهای بزرگتر |
| الگوی کلاسی / شیئی (Class pattern / object pattern) | ساختار با وراثت / با ترکیب اشیاء |
| ترکیب به جای وراثت (Composition over inheritance) | ساختن رفتار با نگه داشتن اشیاء به جای گسترش کلاسها |
| Facade (نما) | interface ِ تازه و سطح بالاتر روی یک زیرسیستم |
| زیرسیستم (Subsystem) | مجموعهٔ کلاسهایی که facade جلویشان است |
| Adapter (مبدل، Wrapper) | یک interface ِ موجود را به آنچه کلاینت انتظار دارد تبدیل میکند |
| Target / Adaptee | interfaceی که کلاینت میخواهد / کلاسی که تطبیق داده میشود |
| Class adapter / object adapter | adapter با وراثت / با نگه داشتن ارجاع |
| Two-way adapter | هر دو interface را پیاده میکند تا هر دو طرف از آن استفاده کنند |
| Composite (مرکب) | درختی که برگ و ظرف در آن interface مشترک دارند |
| Component / Leaf / Composite (شرکتکننده) | interface ِ مشترک / node ِ انتهایی / node ِ دارای فرزند |
| شفافیت در برابر ایمنی (Transparency vs safety) | جای متدهای مدیریت فرزند در Composite و معاملهاش |
| Proxy (نماینده) | جانشینی با همان interface که دسترسی به یک subject را کنترل میکند |
| Subject / RealSubject | interface ِ مشترک / شیء واقعی پشت proxy |
| Remote proxy | نمایندهٔ محلی شیئی در فضای آدرس دیگر |
| Virtual proxy | شیء گران را هنگام نیاز میسازد |
| Protection proxy | قبل از رد کردن، حق دسترسی را چک میکند |
| Smart reference | proxy ای که هنگام دسترسی کار اضافه میکند (شمارش، قفل، بارگذاری) |
| Caching proxy | proxy ای که نتیجهها را ذخیره میکند تا subject صدا زده نشود |
| Copy-on-write | تا وقتی کسی ننوشته شریک باش، بعد کپی کن (GoF: یک بهینهسازی proxy) |
| Lazy Load | الگوی فاولر: بارگذاری داده در اولین دسترسی (relationshipهای Eloquent) |
| Lazy ghost / lazy proxy | lazy objectهای PHP 8.4: مقداردهی درجا / رد کردن به یک نمونهٔ واقعی |
| Decorator (تزئینگر) | همان interface، یک مسئولیت اضافه، روی هم چیدنی |
| Middleware | decorator ای دور یک request handler (PSR-15، Laravel، func(Handler) Handler در Go) |
| Chain of Responsibility (زنجیرهٔ مسئولیت) | الگوی رفتاری: request در طول زنجیره رد میشود؛ هر حلقه میتواند رسیدگی و متوقفش کند |
| Bridge (پل) | سلسلهمراتب abstraction و implementor که با یک ارجاع وصلاند |
| Abstraction / Implementor | سمت رو به کلاینت / سمت وابسته به پلتفرم در Bridge |
| Flyweight (سبکوزن) | شیء مشترکی که state ِ ذاتی را نگه میدارد |
| state ِ ذاتی / بیرونی (Intrinsic / extrinsic state) | مشترک و مستقل از زمینه / وابسته به زمینه و پاس دادهشده |
| Interning | نگه داشتن یک نسخهٔ متعارف از مقدارهای برابر (unique.Make) |
| Static proxy (Laravel) | نامی که Laravel روی facadeهایش گذاشته: فراخوانی استاتیک که به سرویس container رد میشود |
| Real-time facade | facade ِ Laravel که با import کردن Facades\Your\Class ساخته میشود |
getFacadeAccessor | متدی که کلید container پشت یک facade ِ Laravel را برمیگرداند |
__callStatic / __call | متدهای جادویی PHP که فراخوانیهای استاتیک / نمونهای ناشناخته را رد میکنند |
Container::extend | قلاب Laravel برای تزئین یک سرویس resolveشده |
| Service Locator | گرفتن وابستگی با پرسیدن از یک رجیستری (کاری که facadeهای Laravel زیرپوستی میکنند) |
Unwrap | متدی که مقدار پوشیده را برمیگرداند (errorها، ResponseWriter) |
http.ResponseController | helper ِ Go 1.20 که از طریق Unwrap از میان wrapperها به Flush/Hijack میرسد |
RoundTripper | interface ِ Go برای اجرای یک تراکنش HTTP؛ نقطهٔ decorator ِ client با قواعد خودش |
httputil.ReverseProxy | handler ِ reverse proxy در Go؛ با Rewrite پیکربندی کنید (نه Director ِ منسوخ) |
| Devirtualization | تبدیل فراخوانی interface به فراخوانی مستقیم توسط کامپایلر وقتی type را میداند |
| Anti-corruption layer (لایهٔ ضدفساد، ACL) | adapter + facade + translator که یک مدل را از مدل دیگر محافظت میکند |
| API gateway | نقطهٔ ورود واحد: facade (تجمیع) + proxy (مسیریابی، برونسپاری) |
| Sidecar | پروسهٔ کمکی که کنار هر نمونه deploy میشود؛ معمولاً یک proxy (Envoy) |
| Circuit breaker | decorator ای که برای مدتی صدا زدن وابستگی ِ در حال شکست را متوقف میکند |
| PSR-7 / PSR-15 / PSR-18 | استانداردهای PHP برای پیام HTTP / middleware ِ سرور / HTTP client |
| Flysystem | لایهٔ انتزاع فایلسیستم PHP با adapter برای local، FTP، SFTP، S3 و بیشتر |
| Octane | سرور worker ِ بلندعمر Laravel؛ state ِ استاتیک بین requestها زنده میماند |
منابع
- E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4. نسخهٔ درسی (UNC): Structural Patterns intro، Adapter، Bridge، Composite، Decorator، Facade، Flyweight، Proxy، Discussion of Structural Patterns
- Refactoring.Guru: Facade، Adapter، Composite، Proxy، Decorator، Bridge، Flyweight
- packageهای Go: io، bufio، compress/gzip، net/http (
HandlerFunc،RoundTripper،ResponseController،MaxBytesHandler)، net/http/httputil (ReverseProxy،Rewrite)، sync (OnceValues)، unique - بلاگ Go، New unique package
- Laravel 13: Facades، Service Container (
extend)، Middleware، Cache (درایور سفارشی،flexible)، File Storage (Flysystem، فایلسیستم سفارشی)، HTTP Client (retry، middleware ِ Guzzle، macro)، Notifications (کانال سفارشی)، Eloquent Relationships (lazy loading)، Eloquent، Validation - سورس فریمورک Laravel (13.x): Facade.php، Container.php، PendingRequest.php، Macroable.php
- Guzzle، Handlers and Middleware
- PHP-FIG: PSR-7، PSR-15، PSR-18
- مستندات Flysystem
- دفترچهٔ PHP: Lazy Objects، Enumerations basics
- Microsoft Azure Architecture Center: Anti-corruption Layer pattern، Sidecar pattern، API gateways
- Envoy، What is Envoy