Creational Patterns: Singleton, Simple Factory, Factory Method, Abstract Factory, Builder, Prototype
"The important issue in all of this is to ensure that the configuration of services is separated from their use." — Martin Fowler، Inversion of Control Containers and the Dependency Injection pattern، ۲۰۰۴
خلاصه (Summary): الگوهای سازنده (Creational Patterns) تصمیم میگیرند چه کسی new را صدا بزند، کی، و کدام class مشخص ساخته شود. امروز بیشتر این کار را سازندههای ساده بههمراه تزریق وابستگی (Dependency Injection) در ریشهٔ ترکیب (Composition Root) انجام میدهند؛ شش الگوی این صفحه ابزارهاییاند که وقتی خودِ ساختن منطق دارد هنوز سراغشان میروید. تمرکز (Focus): Singleton (و اینکه چرا singletonهای سراسری تست را خراب میکنند)، Simple Factory، Factory Method، Abstract Factory، Builder (بههمراه functional options در Go)، Prototype (کپی سطحی در برابر کپی عمیق)، و کنارشان static factory method، مقداردهی تنبل (Lazy initialization)، object pool، registry، DI container در برابر ضدالگوی service locator، سازندههای دادهٔ تست، و اینکه ساختن اشیا در میکروسرویسها چطور به پیکربندی منتقل میشود. هدف یادگیری (Learning goal): با دیدن کدی پر از new و &T{} و زنجیرهٔ if، مسئلهٔ ساختن را نام ببرید، کوچکترین الگویی را که حلش میکند انتخاب کنید (که اغلب فقط یک سازنده و تزریق است)، آن را به شکل idiomatic در Go و Laravel 13 پیاده کنید و بدون متغیر سراسری تستش کنید.
این صفحه مرجع کامل خانوادهٔ سازنده در کاتالوگ Gang of Four است، بهعلاوهٔ Simple Factory که کتاب Head First مشهورش کرد و ابزارهای امروزی که جای نیمی از آن را گرفتهاند. نقشهٔ هر سه خانواده و تاریخچهٔ کتاب GoF در Design Patterns: introduction است؛ بستهبندی و ترکیب اشیا در Structural Patterns؛ رفتار و الگوریتمها (Strategy، Template Method، Observer) در Behavioral Patterns؛ و ترکیب الگوها و تشخیص سوءاستفاده از آنها در Patterns in practice. دو صفحهٔ SOLID دلیل وجود بیشتر کدهای سازندهاند: Dependency Inversion (به interface وابسته شو، کلاسهای مشخص را در لبه سیمکشی کن) و Open–Closed (محصول تازه اضافه کن بدون ویرایش صدازنندهها).
نقشهٔ صفحه
| اگر دنبال این هستید | بروید به |
|---|---|
| هر شش الگو در دو جدول | همهچیز در یک دقیقه |
| چرا ساختن اصلاً الگو لازم دارد | چرا الگوهای سازنده وجود دارند |
| GoF ۱۹۹۴، Head First، Pike و Cheney، Fowler، Seemann | از کجا آمده |
Singleton، ایمنی در برابر thread، sync.Once، singleton/scoped در Laravel | Singleton |
یک تابع با switch/match | Simple Factory |
| زیرکلاس یا hook تصمیم میگیرد چه محصولی ساخته شود | Factory Method |
| خانوادهای از محصولات که باید با هم جور باشند | Abstract Factory |
| ساخت مرحلهبهمرحله، functional options، builderهای fluent | Builder |
کپی کردن شیء پیکربندیشده، clone، __clone، کپی عمیق | Prototype |
| سازندهٔ نامدار، مقداردهی تنبل، pool، registry، DI، service locator، Object Mother | مفهومهای پشتیبان |
| Go، Laravel، Spring، .NET، TypeScript و Python چطور شیء میسازند | نگاه هر زبان |
| طول عمر در container، قواعد thread-safety، پیامهای خطا | سازوکار |
| کد قبل/بعد | Go، Laravel |
سازندهٔ تلسکوپی، new پراکنده، config سراسری، دادهٔ تست | حل مسئلههای کلاسیک |
| کدام الگو برای کدام وضعیت | انتخاب |
| از مونولیت تا سیستم توزیعشده | در معماری |
| سیستم اعلان با تست، دستبهکار | آزمایشگاه |
| باورهای غلط، چکیده، خودآزمایی، همهٔ اصطلاحها | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
شش الگو. هر سطر پایینتر در بلوک خودش باز میشود.
| الگو | به زبان ساده | مثال کوچک | شکل idiomatic در Go | شکل idiomatic در Laravel |
|---|---|---|---|---|
| Singleton (تکنمونه) | دقیقاً یک نمونه، از همهجا در دسترس | یک شیء config، یک logger | یک بار در main بسازید و پاس بدهید؛ اگر باید تنبل باشد sync.OnceValue | $this->app->singleton()، #[Singleton]، scoped() برای هر درخواست |
| Simple Factory (کارخانهٔ ساده) | یک تابع با switch کلاس را انتخاب میکند | NewChannel("sms") | func New(kind string) (Channel, error) | match در یک کلاس factory یا متد make() روی یک backed enum |
| Factory Method (متد کارخانه) | الگوریتم ثابت است؛ یک hook تعیین میکند کدام محصول | Notifier::notify() متد createChannel() را صدا میزند | creator یک interface یا func() T نگه میدارد | متد abstract که زیرکلاس override میکند |
| Abstract Factory (کارخانهٔ انتزاعی) | یک شیء کل یک خانوادهٔ جور را میسازد | IranKit پیامک + ایمیل + قالببند میسازد | interface با چند متد NewX() | interface که در service provider bind میشود؛ contextual binding برای هر مصرفکننده |
| Builder (سازنده) | شیء پیچیده را گامبهگام بساز، یک بار اعتبارسنجی کن | SmsMessageBuilder::create()->to()->line()->build() | functional options؛ step builder با Build() (T, error) | query builder، Http::withToken()->retry()، MailMessage، model factoryها |
| Prototype (نمونهٔ اولیه) | بهجای ساختن از صفر، از شیء پیکربندیشده کپی بگیر | کلون قالب رسید برای هر tenant | Clone() با maps.Clone/slices.Clone | clone + __clone()، $model->replicate() |
کدام مسئله، کدام ابزار.
| این مسئله را دارید | کوچکترین راهحل | نام الگو، اگر لازم شد |
|---|---|---|
| یک class به همکار نیاز دارد | پارامتر سازنده | تزریق وابستگی (Dependency injection) |
کد کسبوکار new SmtpMailer مینویسد | interface را تزریق کنید، در ریشهٔ ترکیب بسازید | DI + factory در ریشه |
کلاسِ ساختنی به ورودی بستگی دارد ("sms"، "mail") | یک تابع با switch | Simple Factory |
| الگوریتمی قابلاستفادهٔ مجدد باید بسته بماند و محصولها عوض شوند | متد hook یا فیلد تابعی | Factory Method |
| چند محصول همیشه باید از یک خانواده بیایند | یک interface که همه را میسازد | Abstract Factory |
| ده پارامتر اختیاری، invariantهایی برای چک کردن | options یا builder با Build() | Builder |
| ساختن گران است و نسخهها کمی فرق دارند | کپی کن، بعد دست ببر | Prototype |
| دقیقاً یکی در هر پروسه | یک بار در main / singleton در container | Singleton (طول عمر، نه یک static) |
| شیء گران که شاید هیچوقت استفاده نشود | در اولین استفاده بساز | مقداردهی تنبل (Lazy initialization) |
| تخصیصهای کوتاهعمر و پرهزینهٔ زیاد | نمونهها را دوباره استفاده کن | Object pool |
طول عمرهایی که با آنها روبهرو میشوید.
| طول عمر (Lifetime) | Laravel 13 | Go | .NET | Spring |
|---|---|---|---|---|
| هر بار نو (transient) | bind() (پیشفرض برای classهایی که خودکار resolve میشوند) | سازنده را صدا بزنید | AddTransient | scope به نام prototype |
| یکی برای هر درخواست / job | scoped()، #[Scoped] | در handler بسازید و پایین بفرستید؛ مقدارهای درخواست در context | AddScoped | scope به نام request |
| یکی برای هر پروسه | singleton()، #[Singleton]، instance() | در main بسازید؛ متغیر package با sync.OnceValue | AddSingleton | scope به نام singleton (پیشفرض) |
چرا الگوهای سازنده وجود دارند
هر new یک تصمیم است: این class، همین حالا، با این آرگومانها. وقتی این تصمیم داخل کد کسبوکار باشد، سه چیز با هم خراب میشود. کد به یک class مشخص جوش میخورد (نمیتوانید پیامک را از درگاه دیگری بفرستید بدون اینکه سرویس سفارش را ویرایش کنید). کد باید بداند همکارانش را چطور بسازد (credential، URL و timeout به جاهایی نشت میکنند که فقط باید به «پیام بفرست» اهمیت بدهند). و تستها مجبورند چیز واقعی را بسازند (یک اتصال SMTP واقعی) یا متغیرهای سراسری را وصله کنند. الگوهای سازنده این تصمیم را به جای دیگری میبرند: به یک تابع، یک زیرکلاس، یک شیء خانواده، یک builder، یک کپی، یا در کد امروزی، به ریشهٔ ترکیب.
| ساختن داخل کد کسبوکار | ساختن بیرون از آن |
|---|---|
| روز اول ساده خوانده میشود | یک لایهٔ غیرمستقیم بیشتر برای دنبال کردن |
هر صدازننده همان if روی پیکربندی را تکرار میکند | یک جا تصمیم میگیرد |
| عوض کردن پیادهسازی چند فایل را ویرایش میکند | عوض کردن یک binding یا یک factory را ویرایش میکند |
| تست زیرساخت واقعی یا وصلهٔ سراسری لازم دارد | تست fakeها را از سازنده تزریق میکند |
وابستگیهای پنهان (Settings::instance() در عمق کد) | وابستگیها در امضای تابع دیده میشوند |
| ریسک: خشک و تستناپذیر | ریسک: factory برای چیزهایی که هیچوقت عوض نمیشوند (مهندسی بیش از حد) |
تمثیلی که در کل صفحه از آن استفاده میکنیم: ادارهٔ پست. هر شعبه یک رئیس دارد (Singleton، اما شهرداری منصوبش میکند، نه خودش). متصدی باجه به مرسوله نگاه میکند و فرم را انتخاب میکند: نامه، بسته، سفارشی (Simple Factory). هر شعبه همان روال را اجرا میکند اما خودش تصمیم میگیرد کدام پیک ببرد (Factory Method). یک بستهٔ داخلی و یک بستهٔ بینالمللی هر کدام فرم و تمبر و پاکت جور با هم دارند؛ هیچوقت تمبر بینالمللی را روی فرم داخلی نمیگذارید (Abstract Factory). یک مرسولهٔ سفارشی گامبهگام آماده میشود: آدرس، بیمه، کد رهگیری، امضا، و متصدی یک بار قبل از پذیرش همه را چک میکند (Builder). برای ارسال انبوه، از قالب پرشده فتوکپی میگیرید و فقط نام را عوض میکنید (Prototype).
سه بدفهمی رایج، از همین اول
- «همهجا بهجای
newاز factory استفاده کن.» factory فقط وقتی جایش را پس میدهد که ساختن منطق داشته باشد (انتخاب، خانواده، invariant، هزینه). پیشفرض، سازنده بههمراه تزریق است؛ factory برای classی که فقط یک پیادهسازی دارد تشریفات است. - «Singleton یعنی یک نمونه، پس برای هر چیزی که فقط یک بار لازم دارم خوب است.» «فقط یکی» یک تصمیم طول عمر است که مال ریشهٔ ترکیب است. Singleton در GoF چیز دومی هم اضافه میکند، یعنی دسترسی سراسری، و همان است که به تست آسیب میزند و coupling را پنهان میکند.
- «Factory Method یعنی هر متدی که شیء تازه برمیگرداند.» آن static factory method است (سازندهٔ نامدار، مثل
Money::of()یاtime.Now()). Factory Method در GoF یک hook در سلسلهمراتب کلاسهاست (یا در Go یک interface یا مقدار تابعی) که به یک الگوریتم ثابت اجازه میدهد انتخاب محصول را به بعد بسپارد.
تصویر حالت نهاییای است که این صفحه از آن دفاع میکند: factoryها و builderها هنوز هستند، اما از یک جا صدا زده میشوند، یعنی ریشهٔ ترکیب (Composition Root)، و هرچه پایینتر است فقط interface دریافت میکند. نیمهٔ راست چیزی است که باید از آن پرهیز کرد: classهایی که وابستگیشان را از یک container سراسری بیرون میکشند.
از کجا آمده
Gamma، Helm، Johnson، Vlissides، ۱۹۹۴. کتاب Design Patterns: Elements of Reusable Object-Oriented Software (انتشارات Addison-Wesley) ۲۳ الگو را در سه دستهٔ سازنده، ساختاری و رفتاری میچیند. فصل سازندهاش پنج الگو دارد: Abstract Factory، Builder، Factory Method، Prototype و Singleton. متن خود کتاب را در دست نداشتیم؛ جملههای intent زیر همانطور که Wikipedia با شمارهٔ صفحه نقل کرده آمدهاند (منبع دستدوم):
| الگو | intent در GoF (به نقل Wikipedia) |
|---|---|
| Factory Method | "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." |
| Abstract Factory | "Provide an interface for creating families of related or dependent objects without specifying their concrete classes." |
| Builder | "separate the construction of a complex object from its representation"، تا "the same construction process can create different representations" (بازنویسی Wikipedia از صفحهٔ ۹۷ کتاب) |
همان مقالهٔ Wikipedia دربارهٔ Prototype مقایسهٔ کتاب را خلاصه میکند: "designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward abstract factory, prototype, or builder (more flexible, more complex) as the designer discovers where more flexibility is needed."
Freeman و Robson، کتاب Head First Design Patterns، ۲۰۰۴. refactoring.guru Simple Factory را به این کتاب نسبت میدهد: "a class that has one creation method with a large conditional that based on method parameters chooses which product class to instantiate and then return." جزو آن ۲۳ الگو نیست، و refactoring.guru هشداری میدهد که ارزش حفظ کردن دارد: "if you declare a simple factory abstract, it doesn't magically become the abstract factory pattern."
Fowler، ۲۰۰۴. مقالهٔ Inversion of Control Containers and the Dependency Injection pattern نام Dependency Injection را گذاشت، آن را با Service Locator مقایسه کرد و قاعدهای را داد که بالای صفحه نقل شد: پیکربندی سرویسها جدا از استفاده از آنها. به همین دلیل امروز بیشتر کدهای اپلیکیشن factory را مستقیم صدا نمیزنند؛ یک container یا main این کار را میکند.
Seemann، ۲۰۱۰. مقالهٔ Service Locator is an Anti-Pattern استدلال کرد که locator "hides a class' dependencies, causing run-time errors instead of compile-time errors". اصطلاح بعدی او، Composition Root (تنها جایی که گراف اشیا سرهم میشود)، واژهای است که این صفحه به کار میبرد.
Pike و Cheney، ۲۰۱۴. پست Rob Pike با عنوان Self-referential functions and the design of options (ژانویهٔ ۲۰۱۴) ایدهٔ «option بهشکل تابع» را معرفی کرد: "First, we define an option type. It is a function that takes one argument, the Foo we are operating on." سخنرانی Dave Cheney با عنوان Functional options for friendly APIs (اکتبر ۲۰۱۴) آن را به idiom زبان Go برای سازندههای پیکربندیپذیر تبدیل کرد، APIای با "sensible defaults" که "is highly configurable"، "can grow over time" و "self documenting" است. این همان Builder در Go است.
ویژگیهای تازهٔ زبانها که کد سازنده را عوض کردند.
| سال | ویژگی | اثر روی ساختن اشیا |
|---|---|---|
| 2023 | Go 1.21 sync.OnceFunc، sync.OnceValue، sync.OnceValues | singletonهای تنبل و thread-safe در یک خط |
| 2024 | PHP 8.4 lazy objects (ReflectionClass::newLazyGhost()، newLazyProxy()) | مقداردهی تنبل بدون proxy دستنویس |
| 2025 | PHP 8.5 clone($obj, [...]) با بازنویسی property | «wither»های Prototype برای اشیای readonly در یک فراخوانی |
| Laravel 13 docs | attributeهای container: #[Singleton]، #[Scoped]، #[Bind]، #[BindWhen] | خود class طول عمرش را اعلام میکند؛ خط کمتر در provider |
| — | Google Wire (DI زمان کامپایل برای Go) در README خودش "no longer maintained" شده | ریشهٔ ترکیب دستنویس پیشفرض Go است |
مفهومها، یکییکی
هر بلوک یک ترتیب دارد: به زبان ساده، باور غلط رایج، تعریف دقیق، نمودار ساختار و شرکتکنندهها، timeline، سناریوهای واقعی، کد Go و Laravel، پیامدها، کی استفاده نکنیم، الگوهای مرتبط.
Singleton مهم
به زبان ساده: classی که تضمین میکند فقط یکی از آن وجود دارد و به همه راهی میدهد تا به همان یکی برسند.
بدفهمی رایج: «singleton راهِ اشتراک یک pool دیتابیس یا logger است.» اشتراک یک نمونه، تصمیم طول عمر (Lifetime) است و main (یا container) میتواند بدون اطلاع خود class آن را بگیرد. نسخهٔ GoF دسترسی سراسری را هم داخل class میپزد، و همین بخش است که به coupling پنهان و دردسر تست تبدیل میشود.
تعریف: refactoring.guru: "Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance." همان صفحه هزینه را بیپرده فهرست میکند: "Violates the Single Responsibility Principle. The pattern solves two problems at the time"، "can mask bad design"، و "requires special treatment in a multithreaded environment so that multiple threads won't create a singleton object several times."
نیمهٔ چپ تصویر Singleton کلاسیک است: نمونهٔ static خصوصی، سازندهٔ خصوصی، و متد getInstance() که هر کلاینت مستقیم صدا میزند. نیمهٔ راست جایگزین امروزی است: container یا main مالک یک نمونه برای هر طول عمر است و آن را از سازنده به کلاینتها تزریق میکند؛ تست fake خودش را میدهد.
| شرکتکننده (Participant) | نقش | Go | Laravel |
|---|---|---|---|
| Singleton | نمونهٔ یکتا را نگه میدارد، سازنده را پنهان میکند | type خصوصی + متغیر package + sync.Once | private function __construct، static ?self $instance |
getInstance() | ساخت تنبل و دسترسی سراسری | func Instance() *Config | Settings::instance() |
| Client (کلاینت) | از آن استفاده میکند | هر package که import میکند | هر class که صدا میزند |
| جایگزین امروزی | مالک طول عمر است | main یک بار میسازد و pointer پاس میدهد | singleton()، scoped()، #[Singleton] |
Step Goroutine / request Broken lazy singleton sync.Once / OnceValue
1 t0 G1: Instance() sees nil, starts load() enters once.Do, runs load()
2 t0 G2: Instance() also sees nil, starts load() blocks until G1's load() returns
3 t1 G1 assigns instance A returns A
4 t1 G2 overwrites with instance B returns A (same pointer)
5 -- result two configs, a data race one config, race-freeسناریوی واقعی: یک slog.Logger برای کل پروسه؛ یک *sql.DB (مستنداتش میگوید "The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once")؛ یک HTTP client با transport تنظیمشده؛ cache نرخ ارز؛ کلاینت feature flag؛ و در Laravel یک API client بیحالت که با singleton() ثبت شده و context هر tenant که با scoped() ثبت شده.
Go: چهار نسخه از بدترین تا بهترین، و تستی که نشان میدهد sync.OnceValue زیر ۱۰۰ goroutine فقط یک بار initializer را اجرا میکند.
// Package singleton shows four ways to get "one instance" in Go,
// from the broken one to the one we recommend.
package singleton
import (
"os"
"sync"
)
// Config is expensive to build (reads env, files, secrets).
type Config struct {
DSN string
SMSToken string
}
func load() *Config {
return &Config{DSN: os.Getenv("DATABASE_URL"), SMSToken: os.Getenv("SMS_TOKEN")}
}
// 1. Broken: two goroutines can both see nil and both call load
// (a data race; `go test -race` reports it).
var racy *Config
func RacyInstance() *Config {
if racy == nil {
racy = load()
}
return racy
}
// 2. Classic GoF singleton, made thread-safe with sync.Once.
// The return from load "synchronizes before" every return from once.Do.
var (
once sync.Once
instance *Config
)
func Instance() *Config {
once.Do(func() { instance = load() })
return instance
}
// 3. Go 1.21+: the same lazy, thread-safe initialization in one line.
var Shared = sync.OnceValue(load)
// 4. Recommended: "one instance" is a decision of main, not of the type.
// main calls load once and passes the pointer to everyone who needs it;
// tests pass their own Config without touching a global.
type Sender struct{ cfg *Config }
func NewSender(cfg *Config) *Sender { return &Sender{cfg: cfg} }
func (s *Sender) Token() string { return s.cfg.SMSToken }package singleton
import (
"sync"
"sync/atomic"
"testing"
)
func TestOnceValueRunsOnce(t *testing.T) {
var calls atomic.Int32
get := sync.OnceValue(func() *Config { calls.Add(1); return &Config{DSN: "x"} })
var wg sync.WaitGroup
for range 100 {
wg.Add(1)
go func() { defer wg.Done(); _ = get() }()
}
wg.Wait()
if calls.Load() != 1 {
t.Fatalf("initializer ran %d times", calls.Load())
}
}
func TestInjectedConfigNeedsNoGlobal(t *testing.T) {
s := NewSender(&Config{SMSToken: "test-token"})
if s.Token() != "test-token" {
t.Fatal("wrong token")
}
}Laravel: singleton کلاسیک با static، بعد راه container. مستندات container در Laravel 13: "The singleton method binds a class or interface into the container that should only be resolved one time"، و "The scoped method binds a class or interface into the container that should only be resolved one time within a given Laravel request / job lifecycle"، که "when a Laravel Octane worker processes a new request or when a Laravel queue worker processes a new job" پاک میشود.
<?php
// 1. Classic GoF singleton: private constructor, static instance.
// Works, but every caller is hard-wired to it and tests cannot swap it.
namespace App\Legacy;
final class Settings
{
private static ?self $instance = null;
/** @param array<string, mixed> $values */
private function __construct(private array $values) {}
public static function instance(): self
{
// PHP-FPM: one instance per request (share-nothing).
// Octane / queue worker: the same instance lives for many requests.
return self::$instance ??= new self(require base_path('config/settings.php'));
}
public function get(string $key, mixed $default = null): mixed
{
return $this->values[$key] ?? $default;
}
private function __clone() {}
public function __wakeup(): void
{
throw new \LogicException('Cannot unserialize a singleton.');
}
}
// 2. Laravel way: the class is ordinary; the container decides "one instance".
namespace App\Providers;
use App\Services\ExchangeRates;
use App\Services\TenantContext;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// One per process: stateless, expensive to build, safe to share.
$this->app->singleton(ExchangeRates::class, function (Application $app) {
return new ExchangeRates(config('services.rates.url'), $app->make('cache.store'));
});
// One per request / job: holds per-request state (tenant, user).
// Flushed when Octane starts a new request or a worker starts a new job.
$this->app->scoped(TenantContext::class, fn () => new TenantContext());
}
}
// 3. Attribute form (Laravel 13): the class declares its own lifetime.
namespace App\Services;
use Illuminate\Container\Attributes\Scoped;
use Illuminate\Container\Attributes\Singleton;
#[Singleton]
final class ExchangeRates
{
public function __construct(private string $url, private \Illuminate\Contracts\Cache\Repository $cache) {}
}
#[Scoped]
final class TenantContext
{
public ?int $tenantId = null;
}پیامدها: یک نمونه تضمینشده؛ ساخت تنبل؛ اما نقطهٔ دسترسی سراسری، وابستگی پنهان، باگهای ترتیب مقداردهی، حالتی که بین تستها نشت میکند، و در PHP طولانیمدت (Octane، queue worker) حالتی که بین درخواستها نشت میکند.
کی استفاده نکنیم: وقتی «یکی» فقط امروز درست است (امروز یک دیتابیس، فردا read replica)؛ وقتی شیء حالت مخصوص کاربر یا درخواست نگه میدارد؛ وقتی میخواهید صدازنندهها را جدا تست کنید؛ وقتی «singleton» در واقع پیکربندی است (بهجایش یک مقدار پاس بدهید).
مرتبط: Abstract Factory، Builder و Prototype معمولاً بهشکل singleton پیاده میشوند (GoF به نقل Wikipedia)؛ Object pool و Registry پسرعموهای چندنمونهایاش هستند؛ Multiton برای هر کلید یک نمونه نگه میدارد.
Simple Factory حیاتی
به زبان ساده: یک تابع که به ورودی نگاه میکند و تصمیم میگیرد کدام class ساخته شود، تا if بهجای بیست جا در یک جا زندگی کند.
بدفهمی رایج: «Simple Factory همان الگوی Factory Method است.» اصلاً جزو الگوهای GoF نیست. نه hook دارد نه زیرکلاس؛ یک تابع پارامتری با یک شرط است. refactoring.guru آن را "an intermediate step of introducing Factory Method or Abstract Factory patterns" مینامد.
تعریف: یک تابع ساخت (یا classی با یک متد ساخت) که یک تفکیککننده (رشته، enum، مقدار config) میگیرد، interface برمیگرداند و تنها کدی است که نام classهای مشخص را میبرد. اضافه کردن محصول تازه factory را ویرایش میکند؛ این نقض آگاهانه و محلیِ OCP در ازای سادگی است.
در تصویر، کلاینت از ChannelFactory.make(kind) یک کانال میخواهد؛ تنها match در factory است که MailChannel، SmsChannel یا PushChannel را میسازد و کلاینت فقط interface به نام Channel را میبیند.
| شرکتکننده | نقش | مثال |
|---|---|---|
| Client (کلاینت) | محصول را با نوعش میخواهد | OrderShippedListener |
| Factory (کارخانه) | switch/match را نگه میدارد | ChannelFactory::make()، simplefactory.New() |
| Product interface (interface محصول) | چیزی که کلاینت استفاده میکند | Channel |
| Concrete products (محصولات مشخص) | چیزی که factory میسازد | MailChannel، SmsChannel، PushChannel |
Day Change Without a factory With a simple factory
1 D1 add "push" channel edit 7 call sites with if/else edit 1 match, add 1 class
2 D1 -- a call site is missed; push users get email --
3 D9 config typo "smss" silent fallback to mail error: unknown channel "smss"
4 D20 tests need a fake patch 7 places factory or binding returns the fakeسناریوی واقعی: کلاس Illuminate\Database\Connectors\ConnectionFactory در خود Laravel یک simple factory است: createConnector() روی match ($config['driver']) با مقدارهای 'mysql'، 'mariadb'، 'pgsql'، 'sqlite'، 'sqlsrv' کار میکند و connector مناسب را برمیگرداند، و createConnection() همین کار را برای classهای connection میکند. نمونههای واقعی دیگر: factory درگاه پرداخت بر اساس کشور؛ factory parser بر اساس پسوند فایل؛ factory خروجی بر اساس ?format=csv|xlsx.
Go: interface برگردانید و برای نوع ناشناخته error؛ هرگز روی ورودی کاربر panic نکنید.
// Package simplefactory: one function, one switch, returns an interface.
package simplefactory
import (
"context"
"errors"
"fmt"
)
// Channel is the product interface every caller depends on.
type Channel interface {
Send(ctx context.Context, to, body string) error
}
type Email struct{ From string }
type SMS struct{ SenderID string }
type Push struct{ AppID string }
func (e *Email) Send(ctx context.Context, to, body string) error { return nil }
func (s *SMS) Send(ctx context.Context, to, body string) error { return nil }
func (p *Push) Send(ctx context.Context, to, body string) error { return nil }
// Config is what the factory needs to build any channel.
type Config struct {
MailFrom string
SMSID string
PushApp string
}
var ErrUnknownChannel = errors.New("unknown channel")
// New is the simple factory: the only place that knows the concrete types.
// Adding a channel means editing this switch (the OCP cost of the pattern).
func New(kind string, cfg Config) (Channel, error) {
switch kind {
case "email":
return &Email{From: cfg.MailFrom}, nil
case "sms":
return &SMS{SenderID: cfg.SMSID}, nil
case "push":
return &Push{AppID: cfg.PushApp}, nil
default:
return nil, fmt.Errorf("%w: %q", ErrUnknownChannel, kind)
}
}Laravel: همان بهشکل class، و بهشکل backed enum که متد make() آن factory است و tryFrom() ورودی را در لبه اعتبارسنجی میکند. راهنمای PHP: متدهای static روی enum "primarily for alternative constructors" هستند.
<?php
namespace App\Notifications\Channels;
use InvalidArgumentException;
interface Channel
{
public function send(string $to, string $text): void;
}
final class MailChannel implements Channel
{
public function __construct(private string $from) {}
public function send(string $to, string $text): void { /* Mail::raw(...) */ }
}
final class SmsChannel implements Channel
{
public function __construct(private string $senderId) {}
public function send(string $to, string $text): void { /* HTTP call to the gateway */ }
}
// Simple factory as a backed enum: the list of kinds and the creation rule
// live together, and tryFrom() rejects unknown input at the edge.
enum ChannelKind: string
{
case Mail = 'mail';
case Sms = 'sms';
public function make(): Channel
{
return match ($this) {
self::Mail => new MailChannel(config('mail.from.address')),
self::Sms => new SmsChannel(config('services.sms.sender_id')),
};
}
// Static factory method ("named constructor") on the enum.
public static function fromUserPreference(bool $prefersSms): self
{
return $prefersSms ? self::Sms : self::Mail;
}
}
// The same thing as a plain class, the shape Laravel's own
// Illuminate\Database\Connectors\ConnectionFactory uses (match on 'driver').
final class ChannelFactory
{
public function make(string $kind): Channel
{
return match ($kind) {
'mail' => new MailChannel(config('mail.from.address')),
'sms' => new SmsChannel(config('services.sms.sender_id')),
default => throw new InvalidArgumentException("Unsupported channel [{$kind}]."),
};
}
}پیامدها: یک جا classهای مشخص را میشناسد؛ ورودی ناشناخته با صدای بلند شکست میخورد؛ اما شرط بزرگ میشود و هر محصول تازه آن را ویرایش میکند.
کی استفاده نکنیم: وقتی فقط یک محصول هست؛ وقتی pluginهایی از packageهای دیگر باید بدون ویرایش کد شما محصول اضافه کنند (از registry یا hook به نام Manager::extend() در Laravel استفاده کنید)؛ وقتی هر شاخهٔ switch پارامترهای اضافهٔ خودش را میخواهد (به Factory Method یا Abstract Factory بروید).
مرتبط: به Factory Method رشد میکند (شاخهها به زیرکلاس/hook میروند) یا به Abstract Factory (شاخهها خانواده میشوند)؛ نسخهٔ registry بهجای switch یک map دارد.
Factory Method حیاتی
به زبان ساده: یک class روالی ثابت را اجرا میکند و در یک گام از یک hook میپرسد «اینجا از کدام شیء استفاده کنم؟». زیرکلاسها (یا در Go مقداری که وصل میکنید) جواب میدهند.
بدفهمی رایج: «User::create() یا NewServer() همان الگوی Factory Method است.» آنها static factory method هستند (سازندهٔ نامدار). الگوی GoF دربارهٔ سپردن انتخاب به زیرکلاس یا plugin است، در حالی که الگوریتم creator ثابت میماند. این الگو همزاد سازندهٔ Template Method است.
تعریف: refactoring.guru: "Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created." در GoF (به نقل Wikipedia): "let subclasses decide which class to instantiate".
در تصویر، creator انتزاعی یعنی Notifier عملیات notify() را دارد که factory method انتزاعی createChannel() را صدا میزند؛ MailNotifier و SmsNotifier آن را override میکنند و MailChannel یا SmsChannel برمیگردانند. در Go بهجای زیرکلاس، creator یک interface یا مقدار تابعی نگه میدارد.
| شرکتکننده | نقش | PHP | Go |
|---|---|---|---|
| Product (محصول) | interface چیزی که ساخته میشود | Channel | Channel |
| Concrete product (محصول مشخص) | پیادهسازی واقعی | MailChannel، SmsChannel | email، sms |
| Creator (سازنده) | الگوریتم را نگه میدارد، factory method را اعلام میکند | abstract class Notifier با createChannel() | Notifier که یک ChannelCreator نگه میدارد |
| Concrete creator (سازندهٔ مشخص) | factory method را override میکند | MailNotifier، SmsNotifier | EmailCreator، SMSCreator، ChannelFunc |
Step Notifier::notify($to, $text) MailNotifier SmsNotifier
1 validate recipient (shared)
2 $ch = $this->createChannel() ------> new MailChannel(...) new SmsChannel(...)
3 $text = $this->decorate($text) unchanged cut to 160 chars
4 $ch->send($to, $text)
5 -- the algorithm (1..4) never changes; only the hook answers differ --سناریوی واقعی: کلاسهای پایهٔ فریمورک که اجازه میدهند محصول خودتان را وصل کنید: کلاس پایهٔ اعلان با hook به نام createChannel()؛ گزارشسازی که createExporter() آن CSV یا PDF برمیگرداند؛ کلاس پایهٔ مصرفکنندهٔ صف با newHandler()؛ در Go، http.Server تابعهای ConnContext/BaseContext میگیرد و database/sql اجازه میدهد driver اتصالها را از طریق driver.Connector بسازد (sql.OpenDB(c driver.Connector))؛ هر دو hookهای ساخت بهشکل تابع یا interface هستند.
Go: Go ارثبری ندارد، پس «زیرکلاس» به یک مقدار interface یا فیلد تابعی تبدیل میشود. این سادهتر است و در تست یک closure کافی است.
// Package factorymethod: the GoF Factory Method without inheritance.
// The Creator (Notifier) runs the business flow and calls a creation hook;
// concrete creators decide which product the hook returns.
package factorymethod
import (
"context"
"fmt"
"strings"
)
// Product.
type Channel interface {
Send(ctx context.Context, to, body string) error
}
// Creator role: the "factory method" is NewChannel.
type ChannelCreator interface {
NewChannel() Channel
}
// Notifier owns the algorithm; it never names a concrete channel.
type Notifier struct{ creator ChannelCreator }
func NewNotifier(c ChannelCreator) *Notifier { return &Notifier{creator: c} }
func (n *Notifier) Notify(ctx context.Context, to, body string) error {
if strings.TrimSpace(to) == "" {
return fmt.Errorf("notify: empty recipient")
}
ch := n.creator.NewChannel() // the factory method call
return ch.Send(ctx, to, body)
}
// Concrete products.
type email struct{ from string }
type sms struct{ senderID string }
func (e *email) Send(ctx context.Context, to, body string) error { return nil }
func (s *sms) Send(ctx context.Context, to, body string) error { return nil }
// Concrete creators.
type EmailCreator struct{ From string }
func (c EmailCreator) NewChannel() Channel { return &email{from: c.From} }
type SMSCreator struct{ SenderID string }
func (c SMSCreator) NewChannel() Channel { return &sms{senderID: c.SenderID} }
// The Go shortcut: a function type satisfies the creator role,
// so tests and main can pass a closure instead of declaring a type.
type ChannelFunc func() Channel
func (f ChannelFunc) NewChannel() Channel { return f() }Laravel: شکل کتابی با متد abstract، و static factory methodها (Money::of()) برای مقایسه.
<?php
namespace App\Notifications;
use App\Notifications\Channels\Channel;
use App\Notifications\Channels\MailChannel;
use App\Notifications\Channels\SmsChannel;
use InvalidArgumentException;
// Creator: owns the algorithm, defers "which channel" to a subclass.
abstract class Notifier
{
// The factory method.
abstract protected function createChannel(): Channel;
public function notify(string $to, string $text): void
{
if (trim($to) === '') {
throw new InvalidArgumentException('Empty recipient.');
}
$this->createChannel()->send($to, $this->decorate($text));
}
protected function decorate(string $text): string
{
return $text;
}
}
final class MailNotifier extends Notifier
{
protected function createChannel(): Channel
{
return new MailChannel(config('mail.from.address'));
}
}
final class SmsNotifier extends Notifier
{
protected function createChannel(): Channel
{
return new SmsChannel(config('services.sms.sender_id'));
}
protected function decorate(string $text): string
{
return mb_substr($text, 0, 160);
}
}
// Static factory methods (not the GoF pattern, but the everyday Laravel idiom):
// Model::factory(), Carbon::now(), Http::withToken(), Money::of().
final class Money
{
private function __construct(public readonly int $minor, public readonly string $currency) {}
public static function of(int $minor, string $currency): self
{
return new self($minor, strtoupper($currency));
}
public static function zero(string $currency): self
{
return new self(0, strtoupper($currency));
}
}پیامدها: creator برای تغییر بسته و برای محصول تازه باز است (OCP)؛ ساختن در هر زیرکلاس جدا شده؛ اما هر محصول زیرکلاس creator خودش را میخواهد («subclasses proliferate»، به عبارت GoF که بالاتر نقل شد) و ارثبری زیرکلاس را به کلاس پایه گره میزند.
کی استفاده نکنیم: وقتی میتوانید محصول (یا تابعی که آن را میسازد) را بهعنوان آرگومان سازنده پاس بدهید؛ این ترکیب (Composition) است و در Go و در Laravel پر از DI تقریباً همیشه برنده است.
مرتبط: Template Method (الگوریتم creator خودش یک template method است)؛ Abstract Factory (اغلب مجموعهای از factory methodها)؛ Prototype (جایگزینی که زیرکلاس نمیخواهد).
Abstract Factory حیاتی
به زبان ساده: یک شیء که چند چیز مرتبط را میسازد، همه از یک «خانواده»، تا هرگز نتوانید تصادفاً تکهای از خانوادهٔ الف را با تکهای از خانوادهٔ ب قاطی کنید.
بدفهمی رایج: «یک کلاس abstract با متد create() یعنی Abstract Factory.» refactoring.guru: "a lot of people mix-up the abstract factory pattern with a simple factory class declared as abstract. Don't do that!" ویژگی تعیینکننده، چند نوع محصول است که باید با هم جور باشند.
تعریف: refactoring.guru: "Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes." در GoF (به نقل Wikipedia): "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."
در تصویر، کلاینت به interface به نام NotificationKit وابسته است با sms()، mail() و formatter()؛ IranKit و GlobalKit آن را پیاده میکنند و هر کدام یک خانوادهٔ سازگار میسازند، پس کلاینت هرگز نمیتواند پیامک ایرانی را با قالببند انگلیسی قاطی کند.
| شرکتکننده | نقش | مثال |
|---|---|---|
| Abstract factory (کارخانهٔ انتزاعی) | interface با یک متد برای هر محصول | NotificationKit: sms()، mail()، formatter() |
| Concrete factory (کارخانهٔ مشخص) | یکی برای هر خانواده | IranKit، GlobalKit، FakeKit |
| Abstract products (محصولات انتزاعی) | یک interface برای هر نوع محصول | SmsSender، MailSender، Formatter |
| Concrete products (محصولات مشخص) | اعضای یک خانواده | LocalGatewaySms + PersianFormatter؛ GlobalSms + EnglishFormatter |
| Client (کلاینت) | فقط از interfaceها استفاده میکند | ReceiptSender |
Step Without a kit With NotificationKit
1 sms = new LocalGatewaySms(key) kit = container picks IranKit (config: region=ir)
2 fmt = new EnglishFormatter() <-- wrong family sms = kit.sms(); fmt = kit.formatter()
3 send("Paid $12.50") to an Iranian number send("Paid 125,000 IRR")
4 bug found by customers mixing is impossible: one kit, one familyسناریوی واقعی: خانوادههای تأمینکننده برای هر منطقه (درگاه پیامک محلی، relay ایمیل محلی، قالببندی محلی)؛ خانوادههای هر cloud (در AWS کلاینتهای S3 + SQS + KMS، در GCP کلاینتهای GCS + Pub/Sub + Cloud KMS)؛ toolkitهای UI (مثال خود GoF: ویجتها برای هر look-and-feel)؛ خانوادههای test، sandbox و live برای کلاینتهای پرداخت، ایمیل و پیامک.
Go: یک interface با چند سازنده؛ کلاینتها kit را دریافت میکنند.
// Package abstractfactory: one interface that creates a whole family of
// products that must be used together (sender + formatter per region).
package abstractfactory
import (
"context"
"fmt"
)
// Abstract products.
type EmailSender interface {
SendEmail(ctx context.Context, to, subject, html string) error
}
type SMSSender interface {
SendSMS(ctx context.Context, to, text string) error
}
type Formatter interface {
Money(cents int64) string
Direction() string // "ltr" or "rtl"
}
// Abstract factory.
type Kit interface {
Email() EmailSender
SMS() SMSSender
Formatter() Formatter
}
// Family 1: Iran region (local SMS gateway, Persian formatting).
type IranKit struct{ GatewayKey string }
func (k IranKit) Email() EmailSender { return localMail{} }
func (k IranKit) SMS() SMSSender { return localSMS{key: k.GatewayKey} }
func (k IranKit) Formatter() Formatter { return faFormatter{} }
// Family 2: global region (international providers, English formatting).
type GlobalKit struct{ APIKey string }
func (k GlobalKit) Email() EmailSender { return globalMail{} }
func (k GlobalKit) SMS() SMSSender { return globalSMS{key: k.APIKey} }
func (k GlobalKit) Formatter() Formatter { return enFormatter{} }
// Concrete products (bodies trimmed; real ones call HTTP APIs).
type localMail struct{}
type localSMS struct{ key string }
type globalMail struct{}
type globalSMS struct{ key string }
type faFormatter struct{}
type enFormatter struct{}
func (localMail) SendEmail(ctx context.Context, to, subject, html string) error { return nil }
func (localSMS) SendSMS(ctx context.Context, to, text string) error { return nil }
func (globalMail) SendEmail(ctx context.Context, to, subject, html string) error { return nil }
func (globalSMS) SendSMS(ctx context.Context, to, text string) error { return nil }
func (faFormatter) Money(c int64) string { return fmt.Sprintf("%d IRR", c/100) }
func (faFormatter) Direction() string { return "rtl" }
func (enFormatter) Money(c int64) string { return fmt.Sprintf("$%d.%02d", c/100, c%100) }
func (enFormatter) Direction() string { return "ltr" }
// Client code sees only the Kit; it cannot mix an Iran SMS with an English formatter.
func SendReceipt(ctx context.Context, kit Kit, phone string, cents int64) error {
f := kit.Formatter()
return kit.SMS().SendSMS(ctx, phone, "Paid "+f.Money(cents))
}Laravel: kit یک interface است که در service provider bind میشود؛ contextual binding به مصرفکنندههای مختلف خانوادههای مختلف میدهد، یعنی یک Abstract Factory که container پیکربندیاش کرده. مستندات Laravel 13: "two controllers may depend on different implementations of the Illuminate\Contracts\Filesystem\Filesystem contract. Laravel provides a simple, fluent interface for defining this behavior": یعنی when()->needs()->give().
<?php
namespace App\Notifications\Kits;
// Abstract products.
interface SmsSender
{
public function sendSms(string $to, string $text): void;
}
interface MailSender
{
public function sendMail(string $to, string $subject, string $html): void;
}
interface Formatter
{
public function money(int $minor): string;
public function direction(): string;
}
// Abstract factory: one family per region.
interface NotificationKit
{
public function sms(): SmsSender;
public function mail(): MailSender;
public function formatter(): Formatter;
}
final class IranKit implements NotificationKit
{
public function __construct(private string $gatewayKey) {}
public function sms(): SmsSender
{
return new LocalGatewaySms($this->gatewayKey);
}
public function mail(): MailSender
{
return new SmtpMail('mail.local');
}
public function formatter(): Formatter
{
return new PersianFormatter();
}
}
final class GlobalKit implements NotificationKit
{
public function __construct(private string $apiKey) {}
public function sms(): SmsSender
{
return new GlobalSms($this->apiKey);
}
public function mail(): MailSender
{
return new SmtpMail('smtp.global.example');
}
public function formatter(): Formatter
{
return new EnglishFormatter();
}
}
final class LocalGatewaySms implements SmsSender
{
public function __construct(private string $key) {}
public function sendSms(string $to, string $text): void { /* Http::withToken($this->key)->post(...) */ }
}
final class GlobalSms implements SmsSender
{
public function __construct(private string $key) {}
public function sendSms(string $to, string $text): void { /* ... */ }
}
final class SmtpMail implements MailSender
{
public function __construct(private string $host) {}
public function sendMail(string $to, string $subject, string $html): void { /* ... */ }
}
final class PersianFormatter implements Formatter
{
public function money(int $minor): string
{
return number_format(intdiv($minor, 100)).' IRR';
}
public function direction(): string
{
return 'rtl';
}
}
final class EnglishFormatter implements Formatter
{
public function money(int $minor): string
{
return '$'.number_format($minor / 100, 2);
}
public function direction(): string
{
return 'ltr';
}
}
// Client: sees only the kit, so it cannot mix families.
final class ReceiptSender
{
public function __construct(private NotificationKit $kit) {}
public function send(string $phone, int $minor): void
{
$this->kit->sms()->sendSms($phone, 'Paid '.$this->kit->formatter()->money($minor));
}
}پیامدها: خانوادهها سازگار میمانند؛ عوض کردن خانواده یک خط است؛ اما اضافه کردن نوع محصول تازه (مثلاً push()) interface و همهٔ factoryهای مشخص را عوض میکند.
کی استفاده نکنیم: وقتی محصولات واقعاً لازم نیست با هم جور باشند (جدا تزریقشان کنید)؛ وقتی فقط یک خانواده هست و test double هم نیست؛ وقتی «خانواده» در واقع چند مقدار پیکربندی است (یک struct پیکربندی پاس بدهید).
مرتبط: factoryهای مشخص اغلب singleton هستند؛ هر متد اغلب یک factory method است؛ یک kit میتواند prototype نگه دارد و کلونشان کند.
Builder حیاتی
به زبان ساده: یک شیء پیچیده را گامبهگام بسازید (این را تنظیم کن، آن را اضافه کن)، بعد یک بار build() را صدا بزنید که همهچیز را چک میکند و شیء تمامشده و معتبر تحویل میدهد.
بدفهمی رایج: «Builder یعنی فقط زنجیره کردن متدها.» زنجیره کردن (یک fluent interface) نحو است. الگو دربارهٔ جدا کردن ساختن از محصول است: محصول تا build() قابلاستفاده نیست، invariantها در یک دروازه چک میشوند، و همان گامها میتوانند نمایشهای مختلف بسازند. setter زنجیرهای روی یک شیء زنده builder نیست.
تعریف: refactoring.guru: "Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code." و Director اختیاری "defines the order in which to execute the building steps, while the builder provides the implementation for those steps."
در تصویر، یک Director مثل SecurityMessages::otp() گامهای builder را به ترتیب ثابت صدا میزند؛ SmsMessageBuilder حالت را جمع میکند و build() یک بار اعتبارسنجی میکند و SmsMessage تغییرناپذیر برمیگرداند. پایین تصویر شکل Go است: NewClient تابعهای option را روی مقدارهای پیشفرض معقول اعمال میکند.
| شرکتکننده | نقش | مثال |
|---|---|---|
| Builder (سازنده) | متدهای گام، حالت را جمع میکند | SmsMessageBuilder، MessageBuilder |
build() / Build() | تنها دروازهٔ اعتبارسنجی، محصول را برمیگرداند | InvalidArgumentException پرتاب میکند / (Message, error) برمیگرداند |
| Product (محصول) | تمامشده، ترجیحاً تغییرناپذیر | SmsMessage با propertyهای readonly |
| Director (کارگردان، اختیاری) | دستور پخت نامدار روی گامها | SecurityMessages::otp()، builder.PasswordReset() |
| Functional option (در Go) | تابعی که یک فیلد را تنظیم میکند | WithTimeout(3*time.Second) |
Step Telescoping constructor Builder
1 new Sms('+98...', 'hi', 5, null, [], false, null, 'fa') SmsMessageBuilder::create()
2 -- which argument is priority? which is sendAt? -- ->to('+98...')->line('hi')
3 forgot one: TypeError at runtime ->urgent()->tag('otp')
4 invalid combination accepted silently ->build() // validates once, or throwsrefactoring.guru محرک کلاسیک را نام میبرد: "Use the Builder pattern to get rid of a 'telescoping constructor'"، یعنی "a constructor with ten optional parameters".
سناریوی واقعی: query builder در Laravel ("a convenient, fluent interface to creating and running database queries")؛ HTTP client در Laravel (Http::withToken()->timeout(3)->retry(3, 100)->post())؛ MailMessage (->subject()->line()->action())؛ model factoryهای Eloquent (User::factory()->count(3)->suspended()->create())؛ در Go، http.NewRequestWithContext بههمراه setterها، grpc.NewClient(target, opts...) در gRPC و بسیاری از SDKها که functional options میگیرند؛ SQL builderهایی مثل squirrel.
Go: دو شکل. functional options وقتی یک شیء طولانیعمر را پیکربندی میکنید (شکل NewServer(addr, opts...) در کار Cheney)؛ step builder با Build() (T, error) وقتی مقداری با invariant سرهم میکنید.
// Package builder shows the two Go shapes of Builder:
// functional options for configuring a long-lived object (Pike 2014, Cheney 2014),
// and a step builder with Build() for assembling a validated value.
package builder
import (
"errors"
"net/http"
"strings"
"time"
)
// ---- Functional options: Client is configured once, at construction ----
type Client struct {
baseURL string
timeout time.Duration
retries int
token string
http *http.Client
}
// Option mutates a Client under construction.
type Option func(*Client)
func WithTimeout(d time.Duration) Option { return func(c *Client) { c.timeout = d } }
func WithRetries(n int) Option { return func(c *Client) { c.retries = n } }
func WithToken(t string) Option { return func(c *Client) { c.token = t } }
// NewClient has sensible defaults; the zero-option call is the common case.
func NewClient(baseURL string, opts ...Option) *Client {
c := &Client{baseURL: baseURL, timeout: 5 * time.Second, retries: 2}
for _, opt := range opts {
opt(c)
}
c.http = &http.Client{Timeout: c.timeout}
return c
}
// ---- Step builder: Message is assembled, validated, then immutable ----
type Message struct {
To []string
Subject string
Body string
Priority int
Tags []string
}
type MessageBuilder struct {
msg Message
errs []error
}
func NewMessage() *MessageBuilder { return &MessageBuilder{msg: Message{Priority: 5}} }
func (b *MessageBuilder) To(addr string) *MessageBuilder {
if !strings.Contains(addr, "@") && !strings.HasPrefix(addr, "+") {
b.errs = append(b.errs, errors.New("invalid recipient "+addr))
}
b.msg.To = append(b.msg.To, addr)
return b
}
func (b *MessageBuilder) Subject(s string) *MessageBuilder { b.msg.Subject = s; return b }
func (b *MessageBuilder) Body(s string) *MessageBuilder { b.msg.Body = s; return b }
func (b *MessageBuilder) Urgent() *MessageBuilder { b.msg.Priority = 1; return b }
func (b *MessageBuilder) Tag(t string) *MessageBuilder {
b.msg.Tags = append(b.msg.Tags, t)
return b
}
// Build checks the invariants once and returns a copy the caller cannot
// change through the builder.
func (b *MessageBuilder) Build() (Message, error) {
if len(b.msg.To) == 0 {
b.errs = append(b.errs, errors.New("no recipient"))
}
if b.msg.Body == "" {
b.errs = append(b.errs, errors.New("empty body"))
}
if err := errors.Join(b.errs...); err != nil {
return Message{}, err
}
m := b.msg
m.To = append([]string(nil), b.msg.To...)
m.Tags = append([]string(nil), b.msg.Tags...)
return m, nil
}
// Director: a reusable recipe over the builder steps.
func PasswordReset(to, link string) (Message, error) {
return NewMessage().To(to).Subject("Reset your password").
Body("Open " + link + " within 30 minutes.").Urgent().Tag("security").Build()
}Laravel: یک builder روان (fluent) با director، و builderهایی که هر روز استفاده میکنید.
<?php
namespace App\Notifications\Messages;
use InvalidArgumentException;
// Product: immutable once built.
final class SmsMessage
{
/** @param list<string> $tags */
public function __construct(
public readonly string $to,
public readonly string $text,
public readonly int $priority,
public readonly ?\DateTimeImmutable $sendAt,
public readonly array $tags,
) {}
}
// Builder: fluent steps, validation in build().
final class SmsMessageBuilder
{
private ?string $to = null;
private string $text = '';
private int $priority = 5;
private ?\DateTimeImmutable $sendAt = null;
/** @var list<string> */
private array $tags = [];
public static function create(): self
{
return new self();
}
public function to(string $phone): self
{
$this->to = $phone;
return $this;
}
public function line(string $text): self
{
$this->text = trim($this->text.' '.$text);
return $this;
}
public function urgent(): self
{
$this->priority = 1;
return $this;
}
public function at(\DateTimeImmutable $when): self
{
$this->sendAt = $when;
return $this;
}
public function tag(string $tag): self
{
$this->tags[] = $tag;
return $this;
}
public function build(): SmsMessage
{
if ($this->to === null || ! str_starts_with($this->to, '+')) {
throw new InvalidArgumentException('SMS needs an E.164 recipient.');
}
if ($this->text === '' || mb_strlen($this->text) > 160) {
throw new InvalidArgumentException('SMS text must be 1..160 characters.');
}
return new SmsMessage($this->to, $this->text, $this->priority, $this->sendAt, $this->tags);
}
}
// Director: a named recipe over the builder.
final class SecurityMessages
{
public static function otp(string $phone, string $code): SmsMessage
{
return SmsMessageBuilder::create()
->to($phone)
->line("Your code is {$code}.")
->line('It expires in 2 minutes.')
->urgent()
->tag('otp')
->build();
}
}
// Builders you already use in Laravel 13 (each call returns a configured builder):
//
// DB::table('users')->where('active', true)->orderBy('id')->limit(50)->get();
// Http::withToken($token)->timeout(3)->retry(3, 100)->post($url, $payload);
// (new MailMessage)->subject('Invoice paid')->line('Thanks!')->action('View', $url);
// User::factory()->count(3)->suspended()->create();پیامدها: ساختن خوانا؛ invariantها در یک جا؛ محصول تغییرناپذیر؛ اما کد بیشتری از یک سازنده، و builder تغییرپذیری که بین goroutineها یا درخواستها مشترک باشد باگی در کمین است.
کی استفاده نکنیم: برای شیء با دو سه فیلد الزامی (در PHP 8 سازنده با named arguments، در Go struct literal با نام فیلدها)؛ برای پیکربندیای که در واقع یک struct است (یک Config پاس بدهید؛ Cheney همین بدهبستان را بحث میکند).
مرتبط: Abstract Factory محصول را فوراً برمیگرداند و Builder در چند گام؛ Directorی که builder را صدا میزند میتواند خودش یک Factory Method باشد؛ builderها اغلب Composite میسازند.
Prototype مهم
به زبان ساده: یک شیء نمونهٔ کاملاً پیکربندیشده را نگه دارید و شیء تازه را با کپی گرفتن از آن بسازید، بعد همان چند چیزی را که فرق دارد عوض کنید.
بدفهمی رایج: «clone کل شیء را کپی میکند.» در PHP: "When an object is cloned, PHP will perform a shallow copy of all of the object's properties"؛ در Go، c := *t خود struct را کپی میکند اما mapها، sliceها و pointerهای داخلش هنوز به همان داده اشاره میکنند. prototype بدون کپی عمیق (Deep copy) تغییرات را به قالب اصلی پس میدهد.
تعریف: refactoring.guru: "Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes." یک prototype registry "stores a set of pre-built objects that are ready to be copied. The simplest prototype registry is a name → prototype hash map."
در تصویر، کلاینت قالب receipt را با نامش از registry میخواهد و registry نمونهٔ ذخیرهشده را کلون میکند. پایین تصویر تفاوت را نشان میدهد: کپی سطحی (Shallow copy) map را با اصل شریک است و تغییر نشت میکند؛ کپی عمیق در Clone یا __clone map و فهرست خودش را دارد.
| شرکتکننده | نقش | Go | PHP |
|---|---|---|---|
| Prototype (نمونهٔ اولیه) | عملیات کپی را اعلام میکند | Clone() *Template | clone + __clone() |
| Concrete prototype (نمونهٔ مشخص) | از خودش کپی میگیرد، هرجا لازم عمیق | maps.Clone، slices.Clone | __clone() اشیای تودرتو را کلون میکند |
| Registry (اختیاری) | نام → prototype | Registry.New(name) | TemplateRegistry::make() |
| Client (کلاینت) | کپی میخواهد و دستکاریاش میکند | onboarding یک tenant | forTenant('acme') |
Step Shallow copy (bug) Deep copy (Clone / __clone)
1 base.Headers = {X-Brand: acme} same
2 c := *base; c.Headers["X-Brand"] = "tenant-42" c := base.Clone(); c.Headers["X-Brand"] = "tenant-42"
3 base.Headers["X-Brand"] == "tenant-42" <-- leaked base.Headers["X-Brand"] == "acme"
4 every later tenant gets the wrong brand each copy owns its mapسناریوی واقعی: قالبهای اعلان هر tenant که از یک پایهٔ parseشده کلون میشوند؛ موجودیتهای بازی که از یک archetype پیکربندیشده ساخته میشوند؛ replicate() در Eloquent ("You may create an unsaved copy of an existing model instance using the replicate method")؛ http.Request.Clone(ctx) در net/http؛ متدهای تغییرناپذیر withHeader() در PSR-7 که کپی تغییریافته برمیگردانند؛ fixtureهای تست که از یک شیء مرجع کپی میشوند.
Go: یک Clone() صریح که mapها و sliceها را عمیق کپی میکند، بههمراه تستی که نشت کپی سطحی را نشان میدهد.
// Package prototype: copy a configured object instead of rebuilding it,
// and make the copy deep where it holds maps and slices.
package prototype
import (
"fmt"
"maps"
"slices"
)
// Template is costly to build: parsed layout, default headers, channel list.
type Template struct {
Name string
Layout string
Headers map[string]string
Channels []string
}
// ShallowCopy shows the bug: the copy shares the map and the slice array.
func (t *Template) ShallowCopy() *Template {
c := *t
return &c
}
// Clone is the Prototype operation: a deep copy that owns its own data.
func (t *Template) Clone() *Template {
return &Template{
Name: t.Name,
Layout: t.Layout,
Headers: maps.Clone(t.Headers),
Channels: slices.Clone(t.Channels),
}
}
// Registry keeps ready-made prototypes by name and hands out copies.
type Registry struct{ protos map[string]*Template }
func NewRegistry() *Registry { return &Registry{protos: map[string]*Template{}} }
func (r *Registry) Register(p *Template) { r.protos[p.Name] = p }
func (r *Registry) New(name string) (*Template, error) {
p, ok := r.protos[name]
if !ok {
return nil, fmt.Errorf("prototype %q not registered", name)
}
return p.Clone(), nil
}package prototype
import "testing"
func TestCloneIsDeep(t *testing.T) {
base := &Template{Name: "receipt", Headers: map[string]string{"X-Brand": "acme"}, Channels: []string{"mail"}}
shallow := base.ShallowCopy()
shallow.Headers["X-Brand"] = "changed"
if base.Headers["X-Brand"] != "changed" {
t.Fatal("expected the shallow copy to share the map")
}
base.Headers["X-Brand"] = "acme"
deep := base.Clone()
deep.Headers["X-Brand"] = "tenant-42"
deep.Channels[0] = "sms"
if base.Headers["X-Brand"] != "acme" || base.Channels[0] != "mail" {
t.Fatal("clone leaked into the prototype")
}
}Laravel / PHP 8.4: __clone() کپی را عمیق میکند؛ value objectهای readonly از «wither» استفاده میکنند. PHP 8.5 تابع clone($this, ['city' => $city]) را اضافه میکند: راهنما میگوید "the overrides are applied after __clone() has run" و "Readonly properties can be updated on the copy".
<?php
namespace App\Notifications\Templates;
final class Recipient
{
public function __construct(public string $name, public string $email) {}
}
final class EmailTemplate
{
/**
* @param array<string, string> $headers
* @param list<Recipient> $cc
*/
public function __construct(
public string $name,
public string $layout,
public array $headers,
public array $cc,
public \DateTimeImmutable $createdAt,
) {}
// clone is shallow: arrays are copied by value, but objects inside them
// (Recipient) are shared handles. __clone runs on the copy to deepen it.
public function __clone(): void
{
$this->cc = array_map(fn (Recipient $r) => clone $r, $this->cc);
// DateTimeImmutable never changes, so sharing it is safe.
}
public function forTenant(string $brand): self
{
$copy = clone $this;
$copy->headers['X-Brand'] = $brand;
return $copy;
}
}
// Prototype registry: pre-built templates handed out as copies.
final class TemplateRegistry
{
/** @var array<string, EmailTemplate> */
private array $prototypes = [];
public function register(EmailTemplate $prototype): void
{
$this->prototypes[$prototype->name] = $prototype;
}
public function make(string $name): EmailTemplate
{
$prototype = $this->prototypes[$name]
?? throw new \InvalidArgumentException("Template [{$name}] not registered.");
return clone $prototype;
}
}
// Readonly value objects: a "wither" returns a modified copy.
final class Address
{
public function __construct(public readonly string $city, public readonly string $zip) {}
// PHP 8.4: build a new instance (readonly props cannot be written after clone
// outside __clone).
public function withCity(string $city): self
{
return new self($city, $this->zip);
}
// PHP 8.5+: clone() as a function with property overrides:
// return clone($this, ['city' => $city]);
}
// Eloquent's own prototype: $model->replicate() copies attributes into a new,
// unsaved model (no primary key, no timestamps).
// $draft = $invoice->replicate()->fill(['status' => 'draft']);پیامدها: ساختن ارزان اشیای پیشپیکربندیشده؛ بدون زیرکلاس برای هر گونه؛ اما کپی عمیق کار خودتان است، چرخهها و منابع (file handle، socket، اتصال دیتابیس) نباید کپی شوند، و کدی که به هویت شیء تکیه دارد ممکن است بشکند.
کی استفاده نکنیم: وقتی ساختن ارزان است (سازنده را صدا بزنید)؛ وقتی شیء منبع نگه میدارد؛ وقتی builder با director گونهها را روشنتر بیان میکند.
مرتبط: Abstract Factory میتواند prototypeها را نگه دارد و کلون کند؛ طراحیهایی که سنگین از Composite و Decorator استفاده میکنند از Prototype سود میبرند (GoF به نقل Wikipedia).
مفهومهای پشتیبان
Static factory method و سازندهٔ نامدار (Named constructor) حیاتی
به زبان ساده: یک متد static (در PHP) یا تابع سطح package (در Go) با نامی خوب که نمونهٔ تازه برمیگرداند: Money::of(100, 'EUR')، Carbon::now()، time.Unix(0, 0)، errors.New("x").
بدفهمی رایج: «این همان الگوی Factory Method است.» نیست؛ hook ندارد. با این حال رایجترین ابزار ساختن در کد واقعی است، چون یک نام بیشتر از new حرف میزند و میتواند نمونهٔ cacheشده، زیرنوع یا error برگرداند.
تعریف: Effective Go سازندهها را تابعهای معمولی توصیف میکند: "the function to make new instances of ring.Ring—which is the definition of a constructor in Go—would normally be called NewRing"، یا فقط New وقتی package یک type صادر میکند. modelهای Laravel از طریق trait به نام HasFactory متد User::factory() دارند؛ enumهای PHP از متد static بهعنوان "alternative constructors" استفاده میکنند.
| شکل | مثال | چرا نام کمک میکند |
|---|---|---|
New / NewT در Go | bufio.NewReader(r)، ring.New(n) | ورودی را اعتبارسنجی میکند، پیشفرض میگذارد، error برمیگرداند |
| مقدار صفر (Zero value) در Go | var mu sync.Mutex | اصلاً سازنده لازم نیست: "the zero value for a sync.Mutex is defined to be an unlocked mutex" (Effective Go) |
| سازندهٔ نامدار در PHP | Money::of()، Money::zero() | دو سازنده با معنای متفاوت |
| متد static روی enum در PHP | Size::fromLength(120) | نگاشت ورودی به یک case |
| Laravel | User::factory()، Http::withToken()، Str::of() | نقطهٔ ورود به یک builder |
مقداردهی تنبل (Lazy initialization) مهم
به زبان ساده: شیء گران را نسازید تا وقتی کسی واقعاً از آن استفاده کند.
بدفهمی رایج: «تنبل همیشه سریعتر است.» هزینه را به اولین درخواست منتقل میکند (جهش تأخیر cold start) و خطاها را از زمان راهاندازی به زمان اجرا میبرد: DSN اشتباه را اولین مشتری کشف میکند، نه deploy.
تعریف: ساختن تا اولین دسترسی به تعویق میافتد و thread-safe میشود. در Go: sync.Once ("an object that will perform exactly one action") یا OnceValue در Go 1.21 که release notes دربارهٔ آن میگوید "capture a common use of Once to lazily initialize a value on first use". در PHP 8.4: "A lazy object is an object whose initialization is deferred until its state is observed or modified"، با دو راهبرد، "Ghost Objects and Virtual Proxies"؛ "Lazy objects were introduced in PHP 8.4." در Laravel: service providerهای deferred و closure داخل bind()/singleton() همین حالا ساختن را تا اولین make() عقب میاندازند.
Request Eager (build in main) Lazy (OnceValue / closure binding)
1 boot connect to SMS gateway: 300 ms, fail fast nothing
2 #1 send: 5 ms first use: connect 300 ms + send 5 ms
3 #2 send: 5 ms send: 5 ms
4 bad key deploy fails health check first customer gets a 500Object pool (استخر اشیا) تکمیلی
به زبان ساده: مجموعهای از اشیای از قبل ساختهشده نگه دارید و بهجای ساختن تازه، آنها را قرض بدهید.
بدفهمی رایج: «همهچیز را pool کن تا حافظه صرفهجویی شود.» poolها باگ میآورند (فراموش کردن reset، استفاده از شیء بعد از برگرداندن) و فقط برای تخصیصهای گران یا خیلی پرتکرار میارزند. مستندات Go: sync.Pool "is not suitable for all free lists".
تعریف: sync.Pool در Go: "A Pool is a set of temporary objects that may be individually saved and retrieved. Any item stored in the Pool may be removed automatically at any time without notification." و "purpose is to cache allocated but unused items for later reuse, relieving pressure on the garbage collector"؛ مثال استاندارد بافرهای خروجی package به نام fmt است. connection poolها (*sql.DB در database/sql، PgBouncer، PDO هر worker در Laravel زیر Octane) object pool برای اتصالها هستند؛ ببینید Connection Pooling.
// Package pool: an object pool for short-lived, allocation-heavy values.
package pool
import (
"bytes"
"sync"
)
var buffers = sync.Pool{New: func() any { return new(bytes.Buffer) }}
// Render borrows a buffer, uses it, resets it and gives it back.
// Never keep a reference to a pooled object after Put.
func Render(name, body string) string {
buf := buffers.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
buffers.Put(buf)
}()
buf.WriteString("Hello ")
buf.WriteString(name)
buf.WriteString(",\n\n")
buf.WriteString(body)
return buf.String() // String copies, so returning it is safe
}Registry و Multiton تکمیلی
به زبان ساده: یک map شناختهشده از نام به شیء یا سازنده؛ Multiton یعنی یک singleton برای هر کلید.
بدفهمی رایج: «registry همان service locator است، پس همیشه بد است.» registryای از pluginها که هنگام راهاندازی پر میشود (driverها، codecها، کانالها) نقطهٔ توسعهٔ خوبی است. وقتی ضدالگو میشود که کد کسبوکار وابستگیهایش را از آن بیرون بکشد.
تعریف: Fowler (کاتالوگ Patterns of Enterprise Application Architecture): "A well-known object that other objects can use to find common objects and services." package به نام database/sql در Go نمونهٔ مرجع است: "Register makes a database driver available by the provided name. If Register is called twice with the same name or if driver is nil, it panics." driverها در init() تابع sql.Register را صدا میزنند و sql.Open("pgx", dsn) factory را با نام پیدا میکند. کلاس Illuminate\Support\Manager در Laravel یک registry بهعلاوهٔ factory است: driver($name) نمونهها را cache میکند ($this->drivers[$driver] ??= $this->createDriver($driver))، متد create{Name}Driver() یا closureای را که با extend() ثبت شده صدا میزند، و در غیر این صورت Driver [x] not supported. پرتاب میکند. cache، session، mail و کانالهای اعلان همه همینطور ساخته شدهاند.
تزریق وابستگی و ریشهٔ ترکیب (Dependency injection و Composition root) حیاتی
به زبان ساده: یک class چیزهایی را که لازم دارد (معمولاً از طریق سازنده) دریافت میکند، بهجای اینکه خودش بسازد یا جستوجو کند؛ همهٔ ساختن در یک جا در لبهٔ برنامه انجام میشود.
بدفهمی رایج: «DI به container نیاز دارد.» در Go ریشهٔ ترکیب همان main است و DI یعنی پاس دادن آرگومان. container (مال Laravel، Spring، .NET) سیمکشی را خودکار میکند؛ اصل را عوض نمیکند.
تعریف: DI خانهٔ امروزی بیشتر تصمیمهای ساختن است: طول عمر (singleton/scoped/transient) یک تنظیم container است؛ «کدام پیادهسازی» یک binding یا یک switch در main است؛ خانوادهها یک kit بستهشدهاند. Laravel 13: "Laravel's service container implements the PSR-11 interface"، classهایی را که فقط type مشخص لازم دارند با "zero configuration" resolve میکند، و اجازهٔ bind، singleton، scoped، instance، extend، tag و when()->needs()->give() را میدهد. factoryها درون ریشهٔ ترکیب زنده میمانند.
Service locator (ضدالگو) مهم
به زبان ساده: بهجای دریافت وابستگیها، class وسط متدهایش از یک شیء سراسری آنها را میخواهد: app(Mailer::class)، ServiceLocator::get('mailer').
بدفهمی رایج: «facadeهای Laravel و app() service locator هستند، پس Laravel ضدالگوست.» میتوانند اینطور استفاده شوند. تزریق از سازنده در classهای خودتان، و محدود کردن app()/make() به providerها، factoryها و لبههای فریمورک، ریشهٔ ترکیب را سالم نگه میدارد. Fowler (۲۰۰۴) locator و تزریق را دو جایگزین دید؛ Seemann (۲۰۱۰) میگوید locator ضدالگوست چون "hides a class' dependencies, causing run-time errors instead of compile-time errors".
تعریف: registryای که درون کد کسبوکار سازوکار گرفتن وابستگی باشد. نشانهها: سازندههای بیپارامتر، تستهایی که باید container سراسری را پیکربندی کنند، BindingResolutionException در production برای مسیری که هیچ تستی پوشش نداده.
Step Constructor injection Service locator inside a method
1 boot container builds OrderService(Mailer, Sms) container builds OrderService()
2 test new OrderService(new FakeMailer, new FakeSms) must bind fakes in the global container first
3 prod missing binding: fails when the class is built missing binding: fails when ship() runs at 03:00
4 read signature lists every dependency open the method body to find outسازندهٔ دادهٔ تست، Object Mother و model factoryها مهم
به زبان ساده: الگوهای سازنده برای تست: سریع نمونههای معتبر بسازید و فقط چیزی را که تست دربارهٔ آن است بازنویسی کنید.
بدفهمی رایج: «یک فایل fixture غولپیکر سادهتر است.» fixtureهای مشترک هر تست را به هر فیلد گره میزنند؛ builder با پیشفرضهای معتبر اجازه میدهد هر تست فقط فیلد مورد نظرش را بگوید.
تعریف: Fowler: "An object mother is a kind of class used in testing to help create example objects that you use for testing." یک test data builder همان Builder با پیشفرضهای معتبر است. factoryهای Eloquent در Laravel هر دو هستند: "Laravel allows you to define a set of default attributes for each of your Eloquent models using model factories"؛ stateها گونههای نامدارند؛ make() در حافظه میسازد و create() ذخیره میکند. در Go همین کار با تابعهایی مثل newTestUser(t, func(u *User) { u.Locale = "fa" }) انجام میشود، یعنی شکل functional options برای دادهٔ تست.
<?php
// Creation for tests: Eloquent factories (Laravel's builder + prototype for
// models), a test data builder, and an object mother.
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/** @extends Factory<User> */
class UserFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'phone' => '+98912'.fake()->numerify('#######'),
'prefers_sms' => false,
'locale' => 'en',
];
}
// States: named variations applied on top of the definition.
public function prefersSms(): static
{
return $this->state(fn (array $attributes) => ['prefers_sms' => true]);
}
public function persian(): static
{
return $this->state(fn (array $attributes) => ['locale' => 'fa']);
}
}
// Usage:
// User::factory()->make(); // in memory, not saved
// User::factory()->count(3)->prefersSms()->create(); // saved
// User::factory()->persian()->prefersSms()->create(['name' => 'Sara']);
namespace Tests\Support;
use App\Models\User;
use App\Notifications\Messages\SmsMessage;
use App\Notifications\Messages\SmsMessageBuilder;
// Object mother: named, ready-made examples shared by many tests.
final class Users
{
public static function iranianSmsCustomer(): User
{
return User::factory()->persian()->prefersSms()->make(['phone' => '+989120000000']);
}
}
// Test data builder: defaults that pass validation; each test overrides one thing.
final class AnSms
{
private SmsMessageBuilder $b;
private function __construct()
{
$this->b = SmsMessageBuilder::create()->to('+989120000000')->line('hello');
}
public static function valid(): self
{
return new self();
}
public function to(string $phone): self
{
$this->b->to($phone);
return $this;
}
public function build(): SmsMessage
{
return $this->b->build();
}
}نگاه هر زبان و فریمورک
| زبان / فریمورک | سازنده | Singleton / طول عمر | Factory | Builder | Prototype |
|---|---|---|---|---|---|
| Go | تابع NewT(...)، مقدار صفر، composite literal | یک بار در main؛ sync.Once، sync.OnceValue | تابعی که interface برمیگرداند؛ فیلدهای func() T؛ registry به نام sql.Register | functional options؛ step builder با Build() | Clone() صریح؛ maps.Clone، slices.Clone؛ http.Request.Clone |
| PHP 8.4 / Laravel 13 | __construct با promoted properties؛ named arguments | singleton، scoped، instance در container؛ #[Singleton]، #[Scoped] | factoryهای match، make() روی enum، Manager::driver()، contextual binding | query builder، PendingRequest (HTTP)، MailMessage، model factoryها | clone + __clone()، replicate()، clone($o, [...]) در PHP 8.5 |
| Java / Spring | new، سازندهها، record | @Scope("singleton") پیشفرض، prototype، request | متدهای @Bean، FactoryBean، ServiceLoader | @Builder در Lombok، StringBuilder، HttpRequest.newBuilder() | Cloneable (بهطور گسترده معیوب شمرده میشود)، copy constructor |
| C# / .NET | سازندهها، object initializer | AddSingleton، AddScoped، AddTransient؛ Lazy<T> | IServiceProvider، IHttpClientFactory، factory delegate | WebApplication.CreateBuilder()، StringBuilder | MemberwiseClone() (سطحی)، record با with |
| TypeScript / Node | constructor، object literal | cache ماژول هر ماژول را singleton میکند | تابعهای factory، providerهای NestJS (useFactory) | builderهای fluent (Knex، API کوئری Prisma) | structuredClone()، spread {...obj} (سطحی) |
| Python | __init__، سازندههای جایگزین با @classmethod | نمونهٔ سطح ماژول؛ functools.cache | تابعها، @classmethod from_x | معمولاً keyword arguments جای builder را میگیرند | copy.copy / copy.deepcopy |
سازوکار
ایمنی singleton و مقدار تنبل در برابر thread حیاتی
| محیط اجرا | «یک نمونه» چطور میشکند | idiom امن |
|---|---|---|
| Go | check-then-set روی متغیر package از چند goroutine (data race؛ go test -race میگیردش) | sync.Once، sync.OnceValue؛ یا ساختن در main پیش از راهاندازی goroutineها |
| Java | double-checked locking بدون volatile (مدل حافظهٔ پیش از Java 5) | idiom کلاس holder، singleton بهشکل enum، یا DI container |
| .NET | مثل Java | Lazy<T> (پیشفرض thread-safe)، AddSingleton |
| PHP-FPM | مسئلهٔ thread نیست: هر درخواست حالت تازهٔ پروسه است، پس singleton استاتیک یک درخواست عمر میکند | برای cache داخل درخواست خوب است؛ برای cache بین درخواستها بیفایده |
| PHP زیر Octane / queue worker / Swoole / RoadRunner | یک worker به درخواستهای زیادی خدمت میکند؛ singleton استاتیک یا container دادهٔ درخواست (کاربر، tenant، locale) را بین درخواستها نگه میدارد | scoped() برای حالت هر درخواست؛ هرگز Request یا container را به singleton تزریق نکنید (مستندات Octane: چنین شیئی "may have a stale version of the container or request on subsequent requests") |
| Node.js | event loop تکthread؛ singletonهای ماژول بین همهٔ درخواستهای همزمان مشترکاند | حالت هر درخواست در scope درخواست (AsyncLocalStorage) |
تضمین مدل حافظهٔ Go همان چیزی است که sync.Once را درست میکند: "the return from f 'synchronizes before' the return from any call of once.Do(f)". دو قاعدهٔ دیگر از مستندات sync: "A Once must not be copied after first use"، و مقدارهای package به نام sync بهطور کلی "should not be copied".
طول عمر و resolve در container لاراول 13 حیاتی
| API | طول عمر | کاربرد معمول |
|---|---|---|
bind(Abstract::class, fn () => ...) | شیء تازه برای هر resolve | helperهای حالتدار، builderها |
bindIf() / singletonIf() | فقط اگر هنوز چیزی bind نشده | پیشفرضهای package که اپ میتواند بازنویسی کند |
singleton() / #[Singleton] | یکی برای هر نمونهٔ اپلیکیشن (زیر Octane یکی برای هر worker) | API clientهای بیحالت، سرویسهای مشتق از config |
scoped() / #[Scoped] | یکی برای هر درخواست یا job صف؛ با درخواست تازهٔ Octane یا job تازه پاک میشود | context هر tenant، cache هر درخواست |
instance($abstract, $object) | همیشه همان شیء دادهشده | تستها ($this->app->instance(...))، اشیای از پیش ساخته |
#[Bind(Impl::class)]، #[Bind(Fake::class, environments: ['local', 'testing'])] | پیادهسازی پیشفرض روی خود interface اعلام میشود | ساختن بر اساس محیط بدون provider |
#[BindWhen(Impl::class, fn () => Feature::active('beta-events'))] | binding شرطی (مستندات: "requires PHP 8.5 or greater") | پیادهسازیهای پشت feature flag با Laravel Pennant |
when(A::class)->needs(I::class)->give(...) | پیادهسازی برای هر مصرفکننده | Abstract Factory برای هر controller/job |
extend(I::class, fn ($service, $app) => ...) | چیزی را که ساخته شده decorate میکند | decoratorهای logging/metrics |
tag([...], 'reports') + tagged('reports') | مجموعهای از bindingها | فهرست pluginها، همهٔ کانالهای اعلان |
make()، makeWith(X::class, ['id' => 1])، app() | همین حالا resolve کن | فقط providerها، factoryها، لبههای فریمورک |
پیامهای خطایی که میبینید مهم
| پیام (عین متن منبع) | کجا | معنا | راهحل |
|---|---|---|---|
sql: unknown driver "pgx" (forgotten import?) | Open در database/sql | هیچ factoryای با این نام ثبت نشده | package درایور را blank-import کنید (_ "github.com/jackc/pgx/v5/stdlib") |
sql: Register called twice for driver pgx | Register در database/sql (panic) | دو package یک نام را ثبت کردهاند | برای هر نام یک driver import کنید |
sql: Register driver is nil | Register در database/sql (panic) | factory نال ثبت شده | باگ در init() درایور |
Target [App\Contracts\Kit] is not instantiable. | BindingResolutionException در Laravel | interface خواسته شده، چیزی bind نشده | در provider bind کنید یا #[Bind] بگذارید |
Target [X] is not instantiable while building [Y]. | همان، تودرتو | یکی از وابستگیهای Y یک interface بیbinding است | X را bind کنید یا برای Y از contextual binding استفاده کنید |
Unresolvable dependency resolving [Parameter #0 [ <required> string $url ]] in class ... | container در Laravel | آرگومان scalar سازنده بدون پیشفرض | bind با closure، makeWith()، یا give() / giveConfig() |
Target class [App\Foo] does not exist. | container در Laravel | غلط تایپی یا مشکل autoload | نام class را درست کنید / composer dump-autoload |
Driver [x] not supported. | Manager::createDriver() در Laravel | نه متد createXDriver() هست نه closure از extend() | درایور را با extend() ثبت کنید |
Unable to resolve NULL driver for [...] | Manager::driver() در Laravel | درایور پیشفرض پیکربندی نشده | پیشفرض را در config بگذارید |
ساختن بر اساس پیکربندی (Configuration-driven creation) مهم
وقتی انتخاب محصول به deploy، tenant یا یک feature flag بستگی دارد، factory پیکربندی را میخواند، نه ثابتهای hard-code را. نسخهای مبتنی بر دیتابیس که در SaaS چند-tenant کاربرد دارد:
-- Which provider family each tenant uses, read once per request (or cached).
CREATE TABLE notification_providers (
tenant_id bigint NOT NULL,
channel text NOT NULL CHECK (channel IN ('mail', 'sms', 'push')),
provider text NOT NULL, -- 'local_gateway', 'global_sms', 'ses', ...
enabled boolean NOT NULL DEFAULT true,
settings jsonb NOT NULL DEFAULT '{}',
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (tenant_id, channel)
);
-- The factory's input for tenant 42:
SELECT channel, provider, settings
FROM notification_providers
WHERE tenant_id = 42 AND enabled;factory مقدار provider را به یک سازنده نگاشت میکند (یک registry)، پس اضافه کردن تأمینکنندهٔ تازه یعنی یک سطر و یک سازندهٔ ثبتشده، نه یک if تازه در کد کسبوکار.
Go
Before
ساختن با منطق کسبوکار قاطی شده: تابع متغیرهای محیطی را میخواند، type مشخص را با if انتخاب میکند و میسازد. بدون credential واقعی تست نمیشود و بدون ویرایش، کانال تازه نمیگیرد.
// Package before: creation scattered through business code.
package before
import (
"context"
"fmt"
"os"
)
type smtpMailer struct{ host string }
type twilioSMS struct{ token string }
func (m *smtpMailer) Send(ctx context.Context, to, body string) error { return nil }
func (s *twilioSMS) Send(ctx context.Context, to, body string) error { return nil }
// OrderShipped decides which concrete class to build, reads env vars itself,
// and cannot be tested without real credentials.
func OrderShipped(ctx context.Context, user map[string]string, orderID int) error {
body := fmt.Sprintf("Order %d shipped", orderID)
if user["prefers_sms"] == "1" {
s := &twilioSMS{token: os.Getenv("TWILIO_TOKEN")} // new #1
return s.Send(ctx, user["phone"], body)
}
m := &smtpMailer{host: os.Getenv("SMTP_HOST")} // new #2
return m.Send(ctx, user["email"], body)
}After
main ریشهٔ ترکیب است: یک بار پیکربندی را میخواند، با یک simple factory kit را انتخاب میکند (Abstract Factory)، یک client را با functional options پیکربندی میکند (Builder)، و interfaceها را به پایین پاس میدهد.
// Command compositionroot: the only place that calls concrete constructors.
// Configuration (env, flags, feature flags) picks the products; everything
// below main receives interfaces.
package main
import (
"context"
"log/slog"
"os"
"academy/creational-patterns/abstractfactory"
"academy/creational-patterns/builder"
)
func kitFor(region string) abstractfactory.Kit {
switch region {
case "ir":
return abstractfactory.IranKit{GatewayKey: os.Getenv("SMS_GATEWAY_KEY")}
default:
return abstractfactory.GlobalKit{APIKey: os.Getenv("SMS_API_KEY")}
}
}
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) // one per process
kit := kitFor(os.Getenv("REGION"))
api := builder.NewClient("https://billing.internal",
builder.WithRetries(3), builder.WithToken(os.Getenv("BILLING_TOKEN")))
_ = api
if err := abstractfactory.SendReceipt(context.Background(), kit, "+989120000000", 125000); err != nil {
logger.Error("receipt failed", "err", err)
os.Exit(1)
}
logger.Info("receipt sent", "region", os.Getenv("REGION"))
}نگاه Go
- سازندهها تابعاند.
NewTمقدار*Tبرمیگرداند (و وقتی ورودی میتواند نامعتبر باشد یکerror). مقدار صفرِ مفید را ترجیح دهید تا بسیاری از typeها اصلاً سازنده نخواهند. - type مشخص برگردان، interface بپذیر توصیهٔ معمول Go برای سازندههاست؛ از یک factory که کل هدفش پنهان کردن type مشخص است interface برگردانید (
simplefactory.New،ProviderFor). - ارثبری نیست، پس Factory Method یک مقدار میشود. فیلد
func() Channelیا یک interface تکمتدی hook است؛ تستها یک closure پاس میدهند. - functional options همان Builder در Go است. نوع option در کار Pike "a function that takes one argument, the Foo we are operating on" است؛ شکل
NewServer(addr, opts...)در کار Cheney بدون آرگومان پیشفرض میدهد و بدون شکستن صدازنندهها رشد میکند. وقتی optionها زیاد و بیشتر دادهاند، بهجایش struct به نامConfigبگذارید. - singletonهای سراسری متغیرهای package هستند. تستها را وابسته به ترتیب میکنند (تستهای
t.Parallel()آنها را شریکاند) و وابستگی را پنهان میکنند. درmainبسازید و pointer پاس بدهید.sync.OnceValueرا فقط برای مقدارهای واقعاً سراسریِ پروسه، تغییرناپذیر و تنبل نگه دارید. - registry برای pluginها idiomatic است.
database/sql،image(image.RegisterFormat) وencoding/gob(gob.Register) همه ثبت در زمانinit()دارند. ثبت را درinit()و جستوجو را در راهاندازی نگه دارید. - فریمورک DI اختیاری است. README پروژهٔ Google Wire حالا میگوید "This project is no longer maintained"؛ fx و dig از Uber هستند؛ بیشتر سرویسهای Go با دست در
mainیا تابعی شبیهwire.goسیمکشی میشوند. - poolها:
sync.Poolبرای بافرها و encoderها؛*sql.DBخودش pool است؛ دورش pool خودتان را نپیچید.
Laravel
Before
همان بو در یک listener: new برای کانالهای مشخص، خواندن env() در زمان اجرا (بعد از config:cache فایل .env دیگر بارگذاری نمیشود)، و یک singleton استاتیک سراسری.
<?php
namespace App\Listeners;
use App\Events\OrderShipped;
use App\Legacy\Settings;
class SendShipmentNotification
{
public function handle(OrderShipped $event): void
{
$user = $event->order->user;
$text = "Order {$event->order->id} shipped";
if ($user->prefers_sms) {
$sms = new \App\Sms\TwilioClient(env('TWILIO_TOKEN')); // new + env() at runtime
$sms->send($user->phone, $text);
} else {
$mailer = new \App\Mail\SmtpMailer(Settings::instance()->get('smtp_host')); // global singleton
$mailer->send($user->email, $text);
}
}
}After
service provider ریشهٔ ترکیب است: kit را بر اساس پیکربندی bind میکند، برای هر مصرفکننده contextual binding میگذارد، یک HTTP client ساختهشده با builder روان را بهعنوان singleton ثبت میکند و با extend() decorate میکند. listener در سازندهاش NotificationKit میگیرد.
<?php
namespace App\Providers;
use App\Http\Controllers\IranCheckoutController;
use App\Http\Controllers\GlobalCheckoutController;
use App\Notifications\Kits\GlobalKit;
use App\Notifications\Kits\IranKit;
use App\Notifications\Kits\NotificationKit;
use App\Services\SmsGatewayClient;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;
// The composition root of a Laravel app: service providers.
class NotificationServiceProvider extends ServiceProvider
{
public function register(): void
{
// bind: a new object on every make() / injection (transient).
$this->app->bind(NotificationKit::class, function (Application $app) {
// Configuration-driven creation: the deploy picks the family.
return match (config('notifications.region')) {
'ir' => new IranKit(config('services.sms_ir.key')),
default => new GlobalKit(config('services.sms_global.key')),
};
});
// Contextual binding: the same interface, a different family per consumer.
$this->app->when(IranCheckoutController::class)
->needs(NotificationKit::class)
->give(fn () => new IranKit(config('services.sms_ir.key')));
$this->app->when(GlobalCheckoutController::class)
->needs(NotificationKit::class)
->give(fn () => new GlobalKit(config('services.sms_global.key')));
// singleton: one HTTP client builder result per process.
$this->app->singleton(SmsGatewayClient::class, fn () => new SmsGatewayClient(
Http::baseUrl(config('services.sms_ir.url'))
->withToken(config('services.sms_ir.key'))
->timeout(3)
->connectTimeout(2)
->retry(3, 100)
));
// extend: decorate whatever the binding creates (logging, metrics).
$this->app->extend(NotificationKit::class, function (NotificationKit $kit, Application $app) {
return $kit; // e.g. new LoggingKit($kit, $app->make('log'))
});
}
}
// Resolving: let the container inject; make() belongs in providers, factories
// and framework edges, not in business code (that would be a service locator).
//
// public function __construct(private NotificationKit $kit) {} // good
// $kit = app(NotificationKit::class); // locator, avoid in domain code
// $client = app()->makeWith(SmsGatewayClient::class, ['tenant' => 42]);نگاه Laravel
- container همان factory شماست. resolve خودکار classهای مشخص را پوشش میدهد؛ interfaceها را یک بار bind کنید؛ در listener، job، controller و action تزریق از سازنده را ترجیح دهید.
- زیر Octane طول عمر مهم است.
singleton()به اندازهٔ عمر worker زنده است؛scoped()برای یک درخواست یا job. مستندات Laravel دقیقاً به همین دلیل از تزریق container یاRequestبه singleton برحذر میدارد. - Managerها factoryهای درایور در Laravel هستند.
Cache::store('redis')،Mail::mailer('ses')،Storage::disk('s3')، کانالهای اعلان: هر کدامManager::driver()+create{Driver}Driver()+extend()برای درایور سفارشی. وقتی N درایور قابلجایگزینی دارید که config انتخابشان میکند، manager خودتان را بنویسید. - کانالهای اعلان یک factory داخلیاند.
via()نام کانالها را برمیگرداند (مستندات: "Notifications may be sent on the mail, database, broadcast, vonage, and slack channels") یا نام class کانال سفارشی با متدsend($notifiable, $notification)؛ فریمورک آن را میسازد و صدا میزند. - builder همهجا. query builder، Eloquent builder،
Http(PendingRequest)،MailMessage، blueprint درSchema، model factoryها: همه روان، همه با یک فراخوانی پایانی (get()،post()،create()) تمام میشوند. - Prototype در Eloquent.
$model->replicate()attributeها را در یک model ذخیرهنشده کپی میکند؛ با یک آرایه میتوانید attributeهایی را کنار بگذارید. - تست، ساختن را عوض میکند نه کد را.
$this->app->instance()/$this->instance()،Notification::fake()،Http::fake(): هر کدام چیزی را که container میساخت جایگزین میکند. - داخل factoryها
config()، هرگزenv(). مستندات پیکربندی Laravel: وقتی پیکربندی cache شد، "the .env file will not be loaded; therefore, the env function will only return external, system level environment variables."
حل مسئلههای کلاسیک
| مسئله | راهحل | چطور | مزیت | هزینه / محدودیت |
|---|---|---|---|---|
| سازندهٔ تلسکوپی (Telescoping constructor) | Builder / functional options / named arguments | گامها + build()؛ NewX(req, opts...)؛ named args در PHP 8 | خوانا، پیشفرض، اعتبارسنجی در یک جا | کد بیشتر؛ builder تغییرپذیر thread-safe نیست |
new Concrete پراکنده در کد کسبوکار | DI + ریشهٔ ترکیب | interface تزریق کن؛ در main/provider بساز | تستپذیر، قابلجایگزینی | یک جای دیگر برای نگاه کردن |
if ($type == ...) تکراری در جاهای زیاد | Simple Factory | یک switch/match | یک ویرایش برای هر نوع تازه | factory را ویرایش میکند (OCP نیست) |
| pluginهایی که packageهای دیگر اضافه میکنند | Registry / extend() در Manager | sql.Register، Manager::extend('x', fn) | باز برای توسعه | برخورد نامها، شگفتی ترتیب init |
| محصولاتی که باید جور باشند | Abstract Factory | یک kit برای هر خانواده | سازگاری تضمینی | نوع محصول تازه همهٔ kitها را ویرایش میکند |
| singleton پیکربندی سراسری تست را میشکند | پیکربندی را بهعنوان مقدار پاس بده | یک بار در main؛ instance() در تست | تست موازی، وابستگی صریح | امضای سازندهٔ طولانیتر |
| شیء گران که کم استفاده میشود | مقداردهی تنبل | sync.OnceValue، binding با closure، lazy objects در PHP 8.4 | راهاندازی سریعتر | خطا در اولین استفاده ظاهر میشود |
| بافرهای کوتاهعمر زیاد | Object pool | sync.Pool | فشار کمتر روی GC | باگ reset؛ فقط برای مسیرهای داغ |
| گونههای هر tenant از یک شیء گران | Prototype + registry | پایه را کلون کن، فیلدها را بازنویسی کن | گونههای ارزان | انضباط کپی عمیق |
| آمادهسازی تست طولانی و شکننده است | سازندهٔ دادهٔ تست / Object Mother / model factory | پیشفرض معتبر + بازنویسی | تست فقط چیز مهم را میگوید | motherهای مشترک میتوانند god-object شوند |
سازندهٔ تلسکوپی
named arguments در PHP 8 بسیاری از موردها را بدون builder حل میکند: new SmsMessage(to: '+98...', text: 'hi', priority: 1). وقتی سراغ builder بروید که بین فیلدها invariant هست (ایمیل موضوع میخواهد؛ پیامک حداکثر ۱۶۰ کاراکتر) یا بخشهای اختیاری تکرارشونده دارید (tagها، گیرندهها، پیوستها). در Go، یک struct به نام Config با نام فیلدها گزینهٔ بیتشریفات است؛ functional options وقتی بهتر است که پیشفرضها منطق دارند یا میخواهید بدون دست زدن به صدازنندهها option اضافه کنید.
singleton پیکربندی سراسری
Settings::instance()->get('x') را با یک مقدار پیکربندی typeدار که از سازنده تزریق میشود جایگزین کنید. در Laravel، شیء config را با singleton() از مقدارهای config() bind کنید؛ در تست از $this->app->instance() یا config(['x' => ...]) استفاده کنید. در Go، پیکربندی را یک بار در main به یک struct parse کنید و پاس بدهید؛ هرگز os.Getenv را در عمق packageها نخوانید.
انتخاب پیادهسازی برای هر محیط
یک نقطهٔ تصمیم داشته باشید: ProviderFor(env) در main زبان Go؛ bind() با match (config(...)) یا #[Bind(Fake::class, environments: ['local', 'testing'])] در Laravel. بقیهٔ کد هرگز محیط را نمیبیند.
انتخاب
| وضعیت | توصیه | تکنیک اضافه | دلیل |
|---|---|---|---|
| یک پیادهسازی، ساختن ساده | سازنده + DI | هیچ | الگو لازم نیست |
| پیادهسازی را config یا ورودی انتخاب میکند | Simple Factory در ریشهٔ ترکیب | interface + error برگردان | یک نقطهٔ تصمیم |
| الگوریتم قابلاستفادهٔ مجدد، محصول در هر زیرنوع فرق دارد | Factory Method | در Go: فیلد interface/func | الگوریتم بسته میماند |
| چند همکار باید از یک خانواده بیایند | Abstract Factory | contextual binding برای هر مصرفکننده | سازگاری |
| پارامترهای اختیاری زیاد، invariant | Builder | Director برای دستورهای رایج | خوانا، اعتبارسنجیشده |
| شیء طولانیعمر پیکربندیپذیر در Go | functional options | پیشفرضها در NewX | بدون شکستن صدازنندهها رشد میکند |
| اشیای گران تقریباً یکسان زیاد | Prototype | registry با نام | گونههای ارزان |
| یکی برای هر پروسه، بیحالت | singleton در container / ساختن در main | sync.OnceValue اگر تنبل | مشترک، اما تزریقشده |
| یکی برای هر درخواست/job (Octane، worker) | scoped() | هرگز در singleton | نشت بین درخواستها نیست |
| درایورهایی که pluginها اضافه میکنند | Registry / Manager | extend()، sql.Register | باز برای توسعه |
| fixtureهای تست | model factoryها / سازندهٔ دادهٔ تست | stateها، sequenceها | تست نیتش را نشان میدهد |
در معماری: از یک پروسه تا سیستم توزیعشده
تصمیمهای ساختن از معماری بالا میروند: در مونولیت classها و bindingها هستند؛ در سیستم توزیعشده پیکربندی، feature flag و service discovery. الگوها عوض نمیشوند؛ جایی که زندگی میکنند عوض میشود.
مونولیت: یک پروسه، یک دیتابیس
همهٔ ساختن در یک ریشهٔ ترکیب انجام میشود: main.go یا service providerها. مثال روزمره: یک فروشگاه Laravel کلاس NotificationKit را از config('notifications.region') bind میکند و به SendShipmentNotification تزریق میکند. مثال production: همان اپ زیر Octane کلاینت HTTP و سرویس نرخ ارز را singleton() و context هر tenant را scoped() نگه میدارد؛ یک قاعدهٔ code review استفاده از app() را داخل app/Domain ممنوع میکند.
مونولیت ماژولار و چند دیتابیس
هر ماژول مالک سرهمکردن خودش است: ماژول Laravel service provider خودش را دارد؛ ماژول Go یک سازنده مثل billing.NewModule(db, clock, kit) صادر میکند و بقیه را internal/ نگه میدارد. ماژولهای دیگر facade ماژول را میگیرند، نه factoryهایش را. با چند دیتابیس، یک factory برای هر نام اتصال (DB::connection('reporting') در Laravel، یک *sql.DB برای هر دیتابیس که در main ساخته میشود در Go) «کدام دیتابیس» را از کد ماژول بیرون نگه میدارد. مثال production: ماژول billing کلاس PaymentGatewayFactory خودش را با contextual binding ثبت میکند تا فقط classهای billing آن را بگیرند.
میکروسرویسها: ساختن آن سوی مرز شبکه
هر سرویس ریشهٔ ترکیب خودش را دارد و «ورودی factory» از کد به پیکربندی deploy منتقل میشود: متغیر محیطی، secretهای mountشده، سرویس پیکربندی. Abstract Factory به این تبدیل میشود که «این deploy از کدام خانوادهٔ تأمینکننده استفاده میکند» (REGION=ir خانوادهٔ ایران را انتخاب میکند)، و feature flagها در زمان اجرا پیادهسازی را انتخاب میکنند (Laravel Pennant با #[BindWhen]، یا یک کلاینت flag در Go). یک جریان معمول:
Step Component Creation decision
1 boot notification-svc main read REGION, SMS_PROVIDER, flags from env/config service
2 boot main kit := kitFor(REGION); client := NewClient(url, WithRetries(3))
3 run order-svc -> Kafka publishes OrderShipped
4 run notification-svc consumer builds message with Builder; kit.SMS().Send(...)
5 run flag "new-sms-gateway" = 10% factory returns NewGatewaySMS for 10% of tenantsچیزی که از مرز رد نمیشود: «singleton» یکی برای هر پروسه است، هرگز یکی برای کل سیستم. دو replica دو logger، دو pool و دو cache دارند.
دادهٔ توزیعشده: replicaها، cacheها و نمونههای زیاد
«دقیقاً یکی» در سطح cluster مسئلهٔ هماهنگی است، نه الگوی سازنده: به انتخاب رهبر یا قفل توزیعشده نیاز دارد (ببینید Leader Election و Distributed Locking). singletonهای سطح پروسه با replicaها چند برابر میشوند: ۲۰ pod × poolی با ۲۵ اتصال = ۵۰۰ اتصال دیتابیس، و به همین دلیل connection pooling و PgBouncer وجود دارند. factoryهایی که بین read replica و primary انتخاب میکنند (پیکربندی اتصال read/write در Laravel، یک DBRouter با دو *sql.DB در Go) ساختن بر اساس پیکربندی در لایهٔ دادهاند؛ cacheهایی که تنبل و برای هر پروسه ساخته میشوند میتوانند در هر replica دادهٔ کهنه نگه دارند.
مسیر مقیاس: ۱×، ۱۰×، ۱۰۰×
| بار | دغدغههای ساختن | چه عوض میشود |
|---|---|---|
| 1× | خوانایی، تستپذیری | سازنده + DI؛ یک ریشهٔ ترکیب |
| 10× | هزینهٔ تخصیص و اتصال | singletonهای پروسه برای کلاینتها و poolها؛ sync.Pool در مسیرهای داغ؛ مقداردهی تنبل برای کلاینتهای کماستفاده؛ انضباط scoped() در Octane |
| 100× | replicaها و منطقههای زیاد | factoryهای مبتنی بر پیکربندی، feature flag، kit برای هر منطقه؛ بودجهٔ اتصال برای هر pod؛ هیچ حالت سطح پروسهای که فرض کند تنهاست |
آزمایشگاه: سیستم اعلان از Factory Method تا Builder
هدف: یک سرویس اعلان را در سه گام بسازید و هر گام را بدون تأمینکنندهٔ واقعی تست کنید.
- Factory Method.
Service.channelFor(kind)(در Go) /NotificationService::channelFor()(در PHP) hookی است که نوع را به کانال نگاشت میکند؛ الگوریتمSendبا اضافه شدن کانال عوض نمیشود. - Abstract Factory.
Providerکانال ایمیل، کانال پیامک و renderer را بهعنوان یک خانواده میسازد؛SandboxProviderوFakeProviderخانوادههای staging و تست هستند. - Builder.
NewMessage(kind).To(...).Subject(...).Body(...).Build()یک بار اعتبارسنجی میکند: گیرندهٔ خالی، ایمیل بیموضوع، پیامک بیش از ۱۶۰ بایت. - ریشهٔ ترکیب.
ProviderFor(env, rec)تنها simple factory است و یک بار صدا زده میشود.
کد Go و تستها:
// Package notify is the lab: a notification system that grows from
// Factory Method (step 1) to Abstract Factory (step 2) and Builder (step 3).
package notify
import (
"context"
"errors"
"fmt"
"strings"
"sync"
)
// ---- Products ----
// Channel delivers one rendered message to one address.
type Channel interface {
Deliver(ctx context.Context, to, text string) error
}
// Renderer turns a message into text for one family (locale, branding).
type Renderer interface {
Render(m Message) string
}
// ---- Step 3: Builder ----
type Message struct {
Kind string // "mail" or "sms"
To string
Subject string
Body string
}
type MessageBuilder struct {
m Message
errs []error
}
func NewMessage(kind string) *MessageBuilder { return &MessageBuilder{m: Message{Kind: kind}} }
func (b *MessageBuilder) To(to string) *MessageBuilder { b.m.To = to; return b }
func (b *MessageBuilder) Subject(s string) *MessageBuilder { b.m.Subject = s; return b }
func (b *MessageBuilder) Body(format string, a ...any) *MessageBuilder {
b.m.Body = fmt.Sprintf(format, a...)
return b
}
func (b *MessageBuilder) Build() (Message, error) {
if b.m.To == "" {
b.errs = append(b.errs, errors.New("missing recipient"))
}
if b.m.Kind == "mail" && b.m.Subject == "" {
b.errs = append(b.errs, errors.New("mail needs a subject"))
}
if b.m.Kind == "sms" && len(b.m.Body) > 160 {
b.errs = append(b.errs, errors.New("sms body over 160 bytes"))
}
return b.m, errors.Join(b.errs...)
}
// ---- Step 2: Abstract Factory (a family per environment) ----
type Provider interface {
Mail() Channel
SMS() Channel
Renderer() Renderer
}
// Recorder is a fake channel that remembers what it was asked to send.
type Recorder struct {
mu sync.Mutex
Sent []string
}
func (r *Recorder) Deliver(ctx context.Context, to, text string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.Sent = append(r.Sent, to+": "+text)
return nil
}
type plainRenderer struct{ prefix string }
func (p plainRenderer) Render(m Message) string {
if m.Subject != "" {
return p.prefix + m.Subject + " | " + m.Body
}
return p.prefix + m.Body
}
// FakeProvider: one recorder for both channels, used by tests.
type FakeProvider struct{ Rec *Recorder }
func (f FakeProvider) Mail() Channel { return f.Rec }
func (f FakeProvider) SMS() Channel { return f.Rec }
func (f FakeProvider) Renderer() Renderer { return plainRenderer{} }
// SandboxProvider: real wiring, but every message is tagged and goes to a recorder.
type SandboxProvider struct{ Rec *Recorder }
func (s SandboxProvider) Mail() Channel { return s.Rec }
func (s SandboxProvider) SMS() Channel { return s.Rec }
func (s SandboxProvider) Renderer() Renderer { return plainRenderer{prefix: "[sandbox] "} }
// ---- Step 1: Factory Method (the Service defers "which channel" to a hook) ----
// Service is the creator; channelFor is its factory method.
type Service struct{ p Provider }
func NewService(p Provider) *Service { return &Service{p: p} }
func (s *Service) channelFor(kind string) (Channel, error) {
switch kind {
case "mail":
return s.p.Mail(), nil
case "sms":
return s.p.SMS(), nil
}
return nil, fmt.Errorf("notify: unknown channel %q", kind)
}
func (s *Service) Send(ctx context.Context, m Message) error {
ch, err := s.channelFor(m.Kind)
if err != nil {
return err
}
return ch.Deliver(ctx, m.To, s.p.Renderer().Render(m))
}
// ProviderFor is the simple factory used once, in main (the composition root).
func ProviderFor(env string, rec *Recorder) (Provider, error) {
switch strings.ToLower(env) {
case "test":
return FakeProvider{Rec: rec}, nil
case "sandbox", "staging":
return SandboxProvider{Rec: rec}, nil
}
return nil, fmt.Errorf("notify: no provider for env %q", env)
}package notify
import (
"context"
"strings"
"testing"
)
func TestBuilderValidates(t *testing.T) {
cases := []struct {
name string
b *MessageBuilder
wantErr string
}{
{"ok mail", NewMessage("mail").To("a@x.io").Subject("Hi").Body("order %d", 7), ""},
{"no recipient", NewMessage("sms").Body("x"), "missing recipient"},
{"mail without subject", NewMessage("mail").To("a@x.io").Body("x"), "needs a subject"},
{"sms too long", NewMessage("sms").To("+98").Body("%s", strings.Repeat("a", 161)), "over 160"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := tc.b.Build()
if tc.wantErr == "" && err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tc.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tc.wantErr)) {
t.Fatalf("want error containing %q, got %v", tc.wantErr, err)
}
})
}
}
func TestServiceUsesTheWholeFamily(t *testing.T) {
rec := &Recorder{}
p, err := ProviderFor("sandbox", rec)
if err != nil {
t.Fatal(err)
}
msg, _ := NewMessage("sms").To("+989120000000").Body("code %d", 4821).Build()
if err := NewService(p).Send(context.Background(), msg); err != nil {
t.Fatal(err)
}
if got := rec.Sent[0]; got != "+989120000000: [sandbox] code 4821" {
t.Fatalf("got %q", got)
}
}
func TestUnknownChannelAndEnv(t *testing.T) {
if _, err := ProviderFor("prod-typo", nil); err == nil {
t.Fatal("want error for unknown env")
}
s := NewService(FakeProvider{Rec: &Recorder{}})
if err := s.Send(context.Background(), Message{Kind: "fax", To: "x"}); err == nil {
t.Fatal("want error for unknown channel")
}
}اجرا:
cd docs/snippets/design/creational-patterns/go
gofmt -l . # no output
go vet ./... # no output
go test ./...
# ok academy/creational-patterns/lab/notify 0.4s
# ok academy/creational-patterns/prototype 0.4s
# ok academy/creational-patterns/singleton 0.4s
go test -race ./singleton/ # RacyInstance is not called by tests; call it from two goroutines to see the race reportنسخهٔ Laravel (classها برای خواندن در یک فایل) و تستش، که abstract factory را با $this->app->instance() در container عوض میکند:
<?php
// Lab: one file for reading; in an app each class gets its own PSR-4 file.
namespace App\Notify;
use InvalidArgumentException;
// ---- Products ----
interface Channel
{
public function deliver(string $to, string $text): void;
}
interface Renderer
{
public function render(Message $m): string;
}
// ---- Step 3: Builder ----
final class Message
{
public function __construct(
public readonly string $kind,
public readonly string $to,
public readonly string $subject,
public readonly string $body,
) {}
}
final class MessageBuilder
{
private string $to = '';
private string $subject = '';
private string $body = '';
private function __construct(private string $kind) {}
public static function mail(): self
{
return new self('mail');
}
public static function sms(): self
{
return new self('sms');
}
public function to(string $to): self
{
$this->to = $to;
return $this;
}
public function subject(string $subject): self
{
$this->subject = $subject;
return $this;
}
public function body(string $body): self
{
$this->body = $body;
return $this;
}
public function build(): Message
{
$errors = [];
if ($this->to === '') {
$errors[] = 'missing recipient';
}
if ($this->kind === 'mail' && $this->subject === '') {
$errors[] = 'mail needs a subject';
}
if ($this->kind === 'sms' && strlen($this->body) > 160) {
$errors[] = 'sms body over 160 bytes';
}
if ($errors !== []) {
throw new InvalidArgumentException(implode('; ', $errors));
}
return new Message($this->kind, $this->to, $this->subject, $this->body);
}
}
// ---- Step 2: Abstract Factory ----
interface Provider
{
public function mail(): Channel;
public function sms(): Channel;
public function renderer(): Renderer;
}
final class Recorder implements Channel
{
/** @var list<string> */
public array $sent = [];
public function deliver(string $to, string $text): void
{
$this->sent[] = "{$to}: {$text}";
}
}
final class PlainRenderer implements Renderer
{
public function __construct(private string $prefix = '') {}
public function render(Message $m): string
{
return $this->prefix.($m->subject !== '' ? "{$m->subject} | {$m->body}" : $m->body);
}
}
final class SandboxProvider implements Provider
{
public function __construct(private Recorder $recorder) {}
public function mail(): Channel
{
return $this->recorder;
}
public function sms(): Channel
{
return $this->recorder;
}
public function renderer(): Renderer
{
return new PlainRenderer('[sandbox] ');
}
}
// ---- Step 1: Factory Method ----
class NotificationService
{
public function __construct(private Provider $provider) {}
// The factory method: subclasses may override to add channels.
protected function channelFor(string $kind): Channel
{
return match ($kind) {
'mail' => $this->provider->mail(),
'sms' => $this->provider->sms(),
default => throw new InvalidArgumentException("Unknown channel [{$kind}]."),
};
}
public function send(Message $m): void
{
$this->channelFor($m->kind)->deliver($m->to, $this->provider->renderer()->render($m));
}
}
// Wiring (in a service provider):
// $this->app->singleton(Recorder::class);
// $this->app->bind(Provider::class, fn ($app) => match (config('notify.env')) {
// 'sandbox', 'testing' => new SandboxProvider($app->make(Recorder::class)),
// default => $app->make(LiveProvider::class),
// });<?php
namespace Tests\Unit;
use App\Notify\MessageBuilder;
use App\Notify\NotificationService;
use App\Notify\Provider;
use App\Notify\Recorder;
use App\Notify\SandboxProvider;
use InvalidArgumentException;
use Tests\TestCase;
class NotifyTest extends TestCase
{
public function test_builder_rejects_mail_without_subject(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('mail needs a subject');
MessageBuilder::mail()->to('a@x.io')->body('hi')->build();
}
public function test_service_uses_the_bound_family(): void
{
$recorder = new Recorder();
// Swap the abstract factory in the container for this test only.
$this->app->instance(Provider::class, new SandboxProvider($recorder));
$service = $this->app->make(NotificationService::class);
$service->send(MessageBuilder::sms()->to('+989120000000')->body('code 4821')->build());
$this->assertSame(['+989120000000: [sandbox] code 4821'], $recorder->sent);
}
public function test_unknown_channel_fails_loudly(): void
{
$this->expectException(InvalidArgumentException::class);
$service = new NotificationService(new SandboxProvider(new Recorder()));
$service->send(new \App\Notify\Message('fax', 'x', '', 'hi'));
}
}آزمایشها:
- کانال
pushرا اضافه کنید. فایلهایی را که ویرایش میکنید بشمارید (انتظار: interface به نامProvider، هر provider، وchannelFor). این هزینهٔ Abstract Factory برای یک نوع محصول تازه است. - خانوادهٔ
LiveProviderرا اضافه کنید. فایلهایی را که ویرایش میکنید بشمارید (انتظار: یک type تازه و یک خط درProviderFor). این سود یک خانوادهٔ تازه است. ProviderForرا با یک registry (map[string]func(*Recorder) Provider) جایگزین کنید و providerها را درinit()ثبت کنید. با مدل درایورdatabase/sqlمقایسه کنید.Recorderرا singleton سطح package کنید و تستهای Go را با-count=2 -shuffle=onاجرا کنید. ببینیدTestServiceUsesTheWholeFamilyپیامهای اجرای قبلی را میخواند؛ بعد به تزریق برگردید.- در Laravel،
Recorderرا باsingleton()ثبت کنید و یک تست دو-درخواستی با معناشناسی Octane اجرا کنید ($this->app->forgetScopedInstances()singletonها را reset نمیکند)؛ بهscoped()تغییر دهید و مقایسه کنید.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
«هر new باید از factory رد شود» | فقط ساختنِ دارای منطق factory میخواهد؛ سازنده + DI پیشفرض است |
| «Singleton راه اشتراک یک نمونه است» | اشتراک تصمیم طول عمر برای main یا container است؛ Singleton در GoF دسترسی سراسری اضافه میکند که بخش مضر است |
«sync.Once singleton من را تستپذیر میکند» | آن را thread-safe میکند؛ هنوز حالت سراسری مشترک بین همهٔ تستهاست |
«یک create() استاتیک همان الگوی Factory Method است» | آن static factory method / سازندهٔ نامدار است؛ الگوی GoF یک hook است که زیرکلاس یا plugin آن را override میکند |
| «یک simple factory انتزاعی یعنی Abstract Factory» | Abstract Factory یک خانواده از چند نوع محصول میسازد |
| «Builder یعنی زنجیره کردن متدها» | زنجیره نحو است؛ الگو ساختن را از یک محصول تمامشده و اعتبارسنجیشده جدا میکند |
«clone همهچیز را کپی میکند» | clone در PHP و *t در Go سطحیاند؛ اشیای تودرتو، mapها و sliceها را باید دستی کپی کرد |
| «facadeهای Laravel هر class را service locator میکنند» | فقط اگر کد کسبوکار وابستگی را از آنها بکشد؛ تزریق از سازنده ریشهٔ ترکیب را نگه میدارد |
| «singletonهای PHP بهخاطر threadها خطرناکاند» | زیر PHP-FPM یک static یک درخواست عمر میکند؛ خطر واقعی workerهای طولانیعمر (Octane، صف) است که حالت را بین درخواستها نشت میدهند |
| «singleton در میکروسرویس یکی برای کل سیستم است» | یکی برای هر پروسه است؛ ۲۰ replica یعنی ۲۰ نمونه |
| «مقداردهی تنبل همیشه بهتر است» | هزینه و خطا را به اولین درخواست میبرد؛ ساختن مشتاقانه در deploy زود شکست میخورد |
| «object pool همهجا حافظه صرفهجویی میکند» | فقط برای تخصیصهای گران یا خیلی پرتکرار کمک میکند و باگ reset و استفاده-بعد-از-برگرداندن میآورد |
چکیده
| موضوع | به خاطر بسپارید |
|---|---|
| پیشفرض | سازنده + تزریق وابستگی؛ factory فقط وقتی ساختن منطق دارد |
| ریشهٔ ترکیب (Composition root) | یک جا (main، service providerها) گراف را میسازد؛ هیچچیز پایینتر برای همکارانش new صدا نمیزند |
| Singleton | طول عمر است، نه static؛ Go: ساختن در main یا sync.OnceValue؛ Laravel: singleton() / scoped() |
| Octane / workerها | scoped() برای حالت هر درخواست؛ هرگز Request یا container را به singleton تزریق نکنید |
| Simple Factory | یک switch/match، interface برمیگرداند، برای نوع ناشناخته error |
| Factory Method | الگوریتم ثابت + hook ساختن؛ در Go فیلد func یا interface |
| Abstract Factory | چند نوع محصول از یک خانواده؛ خانوادهٔ تازه ارزان، نوع محصول تازه گران |
| Builder | گامها + یک build() اعتبارسنج؛ functional options در Go برای سازندههای پیکربندیپذیر |
| Prototype | کپی + دستکاری؛ کپی عمیق mapها، sliceها، اشیای تودرتو؛ replicate() در Eloquent |
| Registry | نام → سازنده، پرشده در راهاندازی (sql.Register، Manager::extend()) |
| Service locator | کشیدن وابستگی درون متدها؛ پنهانشان میکند؛ در کد دامنه نه |
| مقداردهی تنبل | sync.OnceValue، binding با closure، lazy objects در PHP 8.4؛ هزینهاش تأخیر اولین درخواست |
| Object pool | sync.Pool برای بافرها؛ *sql.DB خودش pool است |
| تستها | model factory با state، سازندهٔ دادهٔ تست، instance() / fake از سازنده |
| میکروسرویسها | ورودی factory به config، secret و feature flag تبدیل میشود؛ singletonها برای هر پروسهاند |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — Singleton در GoF دو مسئله را همزمان حل میکند؛ کدام یک دردسر میسازد؟ مهم
پاسخ
پاسخ: یک نمونه را تضمین میکند و دسترسی سراسری به آن میدهد. دسترسی سراسری مسئله است: وابستگی پنهان، حالت مشترک بین تستها و (در PHP طولانیعمر) بین درخواستها. ببینید Singleton.
۲ — چرا sync.Once درست است ولی چک کردن nil نه؟ حیاتی
پاسخ
پاسخ: دو goroutine میتوانند هر دو nil ببینند و هر دو مقداردهی کنند (data race). once.Do تابع f را یک بار اجرا میکند و بنا بر مدل حافظهٔ Go، بازگشت از f پیش از هر بازگشت از once.Do همگام (synchronize) میشود. ببینید ایمنی در برابر thread.
۳ — اپ Laravel شما به Octane میرود و کاربران نام tenant همدیگر را میبینند. کدام binding اشتباه است و چه جایش میآید؟ حیاتی
پاسخ
پاسخ: شیء مخصوص درخواست (context هر tenant) با singleton() bind شده و به اندازهٔ عمر worker زنده است. آن را با scoped() (یا #[Scoped]) bind کنید تا برای هر درخواست یا job پاک شود. ببینید طول عمر در container.
۴ — فرق Simple Factory و الگوی Factory Method چیست؟ حیاتی
پاسخ
پاسخ: Simple Factory یک تابع با شرطی است که class را انتخاب میکند. Factory Method یک hook درون الگوریتم creator است که زیرکلاسها (یا مقدارهای وصلشده) override میکنند تا محصول را انتخاب کنند. ببینید Simple Factory و Factory Method.
۵ — تغییر ارزان و تغییر گران در Abstract Factory را نام ببرید. تکمیلی
پاسخ
پاسخ: خانوادهٔ تازه (یک factory مشخص تازه) ارزان است. نوع محصول تازه (متد تازه روی interface کارخانه) گران است: همهٔ factoryهای مشخص عوض میشوند. ببینید آزمایشگاه، آزمایشهای ۱ و ۲.
۶ — Go، Builder را به شکل idiomatic چطور بیان میکند، و کی بهجایش struct به نام Config میگذارید؟ مهم
پاسخ
پاسخ: functional options (NewClient(url, WithTimeout(...), WithRetries(...))) برای سازندههای پیکربندیپذیر، یا step builder با Build() (T, error) برای مقدارهای اعتبارسنجیشده. وقتی optionها فیلدهای دادهٔ سادهٔ زیاد و بیمنطقاند، Config سادهتر است. ببینید Builder.
۷ — چرا clone در PHP یا c := *t در Go اغلب الگوی Prototype را میشکند؟ مهم
پاسخ
پاسخ: هر دو سطحیاند: اشیای تودرتو (PHP) و mapها، sliceها و pointerها (Go) با اصل شریکاند و تغییر به آن نشت میکند. در __clone() یا Clone() کپی عمیق کنید. ببینید Prototype.
۸ — آیا app(Mailer::class) درون یک سرویس دامنه مشکل است؟ درون یک service provider چطور؟ مهم
پاسخ
پاسخ: درون سرویس دامنه ضدالگوی service locator است: وابستگی پنهانی که در زمان اجرا شکست میخورد. درون provider (ریشهٔ ترکیب) سیمکشی عادی است. ببینید Service locator.
۹ — اگر دو package در Go با یک نام sql.Register را صدا بزنند چه میشود، و اگر import کردن driver را فراموش کنید؟ تکمیلی
پاسخ
پاسخ: Register با sql: Register called twice for driver <name> panic میکند؛ Open مقدار sql: unknown driver "<name>" (forgotten import?) را برمیگرداند. ببینید پیامهای خطا.
۱۰ — در سیستمی با ۳۰ pod، یک HTTP client «singleton» چند نمونه دارد، و چطور در کل cluster دقیقاً یک نمونهٔ فعال داشته باشیم؟ حیاتی
پاسخ
پاسخ: سی تا، یکی برای هر پروسه. «دقیقاً یکی» در سطح cluster هماهنگی میخواهد (انتخاب رهبر یا قفل توزیعشده)، نه الگوی سازنده. ببینید دادهٔ توزیعشده.
۱۱ — کی مقداردهی تنبل انتخاب اشتباهی است؟ مهم
پاسخ
پاسخ: وقتی زود شکست خوردن در deploy مهم است (credential بد باید health check را بشکند)، وقتی تأخیر اولین درخواست مهم است، یا وقتی شیء بههرحال همیشه استفاده میشود. ببینید مقداردهی تنبل.
واژهنامه
| اصطلاح | معنا |
|---|---|
| الگوی سازنده (Creational pattern) | الگویی دربارهٔ اینکه اشیا چطور، کی و از کدام class ساخته شوند |
| Gang of Four (GoF) | Gamma، Helm، Johnson، Vlissides، نویسندگان Design Patterns (۱۹۹۴) |
| Singleton (تکنمونه) | یک نمونه بهعلاوهٔ نقطهٔ دسترسی سراسری (GoF) |
| Simple Factory (کارخانهٔ ساده) | یک تابع ساخت با یک شرط (Head First؛ جزو GoF نیست) |
| Factory Method (متد کارخانه) | hook ساختن که زیرکلاسها یا pluginها override میکنند (GoF) |
| Abstract Factory (کارخانهٔ انتزاعی) | interfaceی که خانوادهای از محصولات مرتبط میسازد (GoF) |
| Builder (سازنده) | ساختن گامبهگام با یک build() پایانی (GoF) |
| Director (کارگردان) | شیء اختیاری که گامهای builder را به ترتیب ثابت اجرا میکند |
| Prototype (نمونهٔ اولیه) | ساختن اشیا با کپی گرفتن از یک نمونهٔ پیکربندیشده (GoF) |
| Prototype registry | map نام → prototype که کلون برمیگرداند |
| Product / concrete product (محصول / محصول مشخص) | interface ساختهشده / پیادهسازی آن |
| Creator / concrete creator (سازنده / سازندهٔ مشخص) | classی که factory method را اعلام / override میکند |
| Product family (خانوادهٔ محصول) | محصولاتی که باید با هم استفاده شوند (یک kit) |
| Static factory method / named constructor (سازندهٔ نامدار) | متد static یا تابعی با نام معنادار که نمونه برمیگرداند |
| Telescoping constructor (سازندهٔ تلسکوپی) | پارامترهای سازندهٔ overloadشده یا اختیاری زیاد |
| Fluent interface (رابط روان) | زنجیرهٔ متدها که builder را برمیگرداند (return $this) |
| Functional options | idiom زبان Go: آرگومانهای variadic از نوع func(*T) که مقدار تازه را پیکربندی میکنند |
| Test data builder (سازندهٔ دادهٔ تست) | builder با پیشفرضهای معتبر برای تست |
| Object Mother | classی از نمونههای نامدار و آماده برای تست (Fowler) |
| Eloquent model factory | کلاس Laravel با definition()، stateها، make() و create() |
| Shallow copy (کپی سطحی) | کپی فیلدهای سطح بالا؛ ارجاعهای تودرتو مشترک میمانند |
| Deep copy (کپی عمیق) | کپیای که اشیای تودرتو، mapها و sliceها را هم تکثیر میکند |
__clone() | متد جادویی PHP که بعد از clone روی کپی اجرا میشود |
replicate() | متد Eloquent که کپی ذخیرهنشده از یک model برمیگرداند |
| Lazy initialization (مقداردهی تنبل) | ساختن در اولین استفاده |
| Lazy ghost / lazy proxy | دو راهبرد lazy object در PHP 8.4: مقداردهی درجا / واگذاری به نمونهٔ واقعی |
sync.Once، sync.OnceValue | ابزارهای Go که یک initializer را دقیقاً یک بار و thread-safe اجرا میکنند |
| Double-checked locking | idiom singleton تنبل در Java/C# که بدون memory barrier درست، شکسته است |
| Object pool (استخر اشیا) | مجموعهای از نمونههای قابلاستفادهٔ مجدد که قرض داده و برگردانده میشوند (sync.Pool) |
| Registry | شیء شناختهشده برای پیدا کردن اشیا و سرویسهای مشترک (Fowler) |
| Multiton | یک نمونه برای هر کلید |
| Manager (در Laravel) | Illuminate\Support\Manager: registry درایور + factory با extend() |
| Dependency injection (تزریق وابستگی) | دادن وابستگیها به شیء بهجای اینکه خودش بسازدشان |
| Composition root (ریشهٔ ترکیب) | تنها جایی که گراف اشیا ساخته میشود (Seemann) |
| DI container | کتابخانهای که سیمکشی و طول عمر را خودکار میکند (container لاراول، Spring، .NET) |
| Service locator | کشیدن وابستگیها از یک registry سراسری درون کد کسبوکار (به نظر Seemann ضدالگو) |
| PSR-11 | interface استاندارد container در PHP (Psr\Container\ContainerInterface) |
| طول عمر: transient / scoped / singleton | هر بار نو / یکی برای هر درخواست یا job / یکی برای هر پروسه |
| Contextual binding (binding زمینهای) | when()->needs()->give() در Laravel: پیادهسازی برای هر مصرفکننده |
| Binding attributes | #[Bind]، #[BindWhen]، #[Singleton]، #[Scoped] در Laravel |
| Feature flag | کلید زمان اجرا که میتواند پیادهسازی برگشتی factory را عوض کند (مثلاً Laravel Pennant) |
| Configuration-driven creation (ساختن بر اساس پیکربندی) | factoryهایی که انتخابشان از config، env، دادهٔ tenant یا flag میآید |
| Laravel Octane | سرور طولانیعمر Laravel؛ singletonها بین درخواستها زندهاند |
| Google Wire | تولیدکنندهٔ کد DI زمان کامپایل برای Go؛ README میگوید دیگر نگهداری نمیشود |
منابع
- Gamma، Helm، Johnson، Vlissides، Design Patterns: Elements of Reusable Object-Oriented Software، Addison-Wesley، ۱۹۹۴ (فصل سازنده). intentها به نقل Wikipedia: Factory method pattern، Abstract factory pattern، Builder pattern، Prototype pattern، Singleton pattern
- Refactoring.guru: Creational patterns، Singleton، Factory Method، Abstract Factory، Builder، Prototype، Factory comparison (Simple Factory)
- Martin Fowler، Inversion of Control Containers and the Dependency Injection pattern، ۲۰۰۴؛ Registry؛ Object Mother
- Mark Seemann، Service Locator is an Anti-Pattern، ۲۰۱۰
- Rob Pike، Self-referential functions and the design of options، ۲۰۱۴
- Dave Cheney، Functional options for friendly APIs، ۲۰۱۴
- Go: Effective Go (سازندهها و composite literal)، package sync (
Once،OnceValue،Pool)، package database/sql (Register،Open)، Go 1.21 release notes، کد منبع database/sql، README پروژهٔ Google Wire - Laravel 13: Service Container، Service Providers، Octane، Eloquent: Factories، Eloquent (replicate)، Notifications، HTTP Client، Query Builder، Pennant
- کد منبع فریمورک Laravel (13.x): Support/Manager.php، Database/Connectors/ConnectionFactory.php، Container/Container.php
- راهنمای PHP: Object cloning، Lazy objects، Enumeration static methods؛ RFC زبان PHP: Clone with v2 (PHP 8.5)