{"id":"6b08bd3d80884893657cca0f","slug":"state","title":"Stan (State): obiekt, który zmienia zachowanie razem z etapem życia","summary":"Wzorzec Stan na przykładzie zamówienia w pierogarni: Nowe, Opłacone, W kuchni, Dostarczone i Anulowane jako osobne obiekty, które same pilnują dozwolonych przejść. Maszyna stanów bez drabinki if-ów, kod w pięciu językach.","servedLang":"pl","availableLangs":["pl","en"],"topics":["state"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","behavioral","state","state-machine","lifecycle"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":12,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:05.764Z","updatedAt":"2026-11-27T10:04:41.885Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"violet","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"Wzorzec projektowy Stan (State) w C#, TypeScript, Java, Go i Python: maszyna stanów zamówienia, dozwolone przejścia, różnica względem Strategii i gotowe biblioteki.","wordCount":2303,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Zamówienie w pierogarni Haliny przechodzi przez kilka etapów: czeka na płatność, jest opłacone, trafia do kuchni, w końcu jedzie do klienta. Anulować można je tylko na początku – gdy pierogi już się gotują, jest za późno. "},{"type":"text","text":"Stan","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"State","marks":[{"type":"italic"}]},{"type":"text","text":") zamienia każdy etap w osobny obiekt, który wie, co w danej chwili wolno, a czego nie."}]},{"type":"callout","attrs":{"variant":"tip","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Zachowanie obiektu zależy od jego "},{"type":"text","text":"stanu","marks":[{"type":"bold"}]},{"type":"text","text":", a każdy stan to osobna klasa z tym samym interfejsem."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Kontekst (zamówienie) "},{"type":"text","text":"deleguje","marks":[{"type":"bold"}]},{"type":"text","text":" wywołania do bieżącego stanu, zamiast sprawdzać "},{"type":"text","text":"if (status == ...)","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Stany "},{"type":"text","text":"same decydują o przejściach","marks":[{"type":"bold"}]},{"type":"text","text":" – zwracają albo ustawiają kolejny stan."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"5","label":"stanów zamówienia","hint":"od Nowego do Dostarczonego lub Anulowanego"},{"value":"4","label":"akcje na zamówieniu","hint":"zapłać, gotuj, dostarcz, anuluj"},{"value":"0","label":"instrukcji switch po statusie","hint":"każda reguła mieszka w swoim stanie"}]}},{"type":"heading","attrs":{"level":2,"id":"problem-ta-sama-drabinka-w-kazdej-metodzie"},"content":[{"type":"text","text":"Problem: ta sama drabinka w każdej metodzie"}]},{"type":"paragraph","content":[{"type":"text","text":"Pole "},{"type":"text","text":"status","marks":[{"type":"code"}]},{"type":"text","text":" i seria warunków wyglądają niewinnie, dopóki akcji nie jest kilka:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"order-before.ts"},"content":[{"type":"text","text":"class Order {\n  status: 'new' | 'paid' | 'in-kitchen' | 'delivered' | 'cancelled' = 'new';\n\n  cancel(): void {\n    if (this.status === 'new' || this.status === 'paid') {\n      this.status = 'cancelled';\n      if (this.status === 'paid') refund(this); // never runs – status was just overwritten\n    } else if (this.status === 'in-kitchen') {\n      throw new Error('Pierogi are already boiling');\n    } else {\n      throw new Error(`Cannot cancel a ${this.status} order`);\n    }\n  }\n  // pay(), startCooking(), deliver(), canEditAddress()... – the same if-ladder in each\n}"}]},{"type":"paragraph","content":[{"type":"text","text":"Każda metoda zawiera własną kopię tej samej drabinki warunków. Dodanie stanu „W drodze” oznacza przejrzenie wszystkich metod – i łatwo którąś pominąć. W kodzie powyżej ukrył się też prawdziwy błąd: zwrot pieniędzy nigdy się nie wykona, bo status został nadpisany linijkę wcześniej. Reguły biznesowe („czy można anulować?”) są rozsiane po klasie i nie da się ich przeczytać w jednym miejscu."}]},{"type":"heading","attrs":{"level":2,"id":"rozwiazanie-kazdy-etap-to-obiekt"},"content":[{"type":"text","text":"Rozwiązanie: każdy etap to obiekt"}]},{"type":"paragraph","content":[{"type":"text","text":"Każdy stan zamówienia staje się klasą implementującą wspólny interfejs z metodami "},{"type":"text","text":"pay()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"startCooking()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"deliver()","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"cancel()","marks":[{"type":"code"}]},{"type":"text","text":". Klasa bazowa domyślnie "},{"type":"text","text":"odrzuca","marks":[{"type":"bold"}]},{"type":"text","text":" każde przejście, a konkretne stany nadpisują tylko te, które są w nich dozwolone. Zamówienie trzyma referencję do bieżącego stanu i deleguje do niego każde wywołanie."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"stateDiagram-v2\n  direction LR\n  [*] --> New\n  New --> Paid : pay()\n  New --> Cancelled : cancel()\n  Paid --> InKitchen : startCooking()\n  Paid --> Cancelled : cancel() + zwrot\n  InKitchen --> Delivered : deliver()\n  Delivered --> [*]\n  Cancelled --> [*]","caption":"Maszyna stanów zamówienia"}},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class Order {\n    -state: OrderState\n    +pay()\n    +startCooking()\n    +deliver()\n    +cancel()\n  }\n  class OrderState {\n    <<abstract>>\n    +customerMessage\n    +pay() OrderState\n    +startCooking() OrderState\n    +deliver() OrderState\n    +cancel() OrderState\n  }\n  Order o--> OrderState : deleguje\n  OrderState <|-- New\n  OrderState <|-- Paid\n  OrderState <|-- InKitchen\n  OrderState <|-- Delivered\n  OrderState <|-- Cancelled","caption":"Struktura wzorca Stan"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Rola"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"W przykładzie"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Odpowiedzialność"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kontekst ("},{"type":"text","text":"Context","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Order","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"przechowuje bieżący stan, deleguje do niego akcje"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stan ("},{"type":"text","text":"State","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"OrderState","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wspólny interfejs; domyślnie odrzuca przejścia"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Konkretny stan"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"New","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Paid","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"InKitchen","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Delivered","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"Cancelled","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zachowanie i dozwolone przejścia jednego etapu"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"implementacja-w-pieciu-jezykach"},"content":[{"type":"text","text":"Implementacja w pięciu językach"}]},{"type":"paragraph","content":[{"type":"text","text":"W tej wersji metody stanów "},{"type":"text","text":"zwracają kolejny stan","marks":[{"type":"bold"}]},{"type":"text","text":", a kontekst go zapisuje. Stany nie mają pól, więc mogą być współdzielone (w Go – jako zmienne pakietu). Poza przejściami każdy stan ma też własne zachowanie: komunikat dla klienta, który aplikacja pokazuje w śledzeniu zamówienia."}]},{"type":"codeGroup","attrs":{"title":"Stan – cykl życia zamówienia"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Order.cs"},"content":[{"type":"text","text":"var order = new Order(42);\norder.Pay();\norder.StartCooking();\nConsole.WriteLine(order.State.CustomerMessage); // We are making your pierogi\ntry { order.Cancel(); }\ncatch (InvalidOperationException e) { Console.WriteLine(e.Message); } // Cannot cancel an order that is InKitchen\norder.Deliver();\n\npublic abstract class OrderState\n{\n    public string Name => GetType().Name;\n    public abstract string CustomerMessage { get; }\n\n    // By default every transition is forbidden; states override only what they allow.\n    public virtual OrderState Pay() => Deny(\"pay\");\n    public virtual OrderState StartCooking() => Deny(\"start cooking\");\n    public virtual OrderState Deliver() => Deny(\"deliver\");\n    public virtual OrderState Cancel() => Deny(\"cancel\");\n\n    private OrderState Deny(string action) =>\n        throw new InvalidOperationException($\"Cannot {action} an order that is {Name}\");\n}\n\npublic sealed class New : OrderState\n{\n    public override string CustomerMessage => \"Waiting for payment\";\n    public override OrderState Pay() => new Paid();\n    public override OrderState Cancel() => new Cancelled();\n}\n\npublic sealed class Paid : OrderState\n{\n    public override string CustomerMessage => \"Payment received\";\n    public override OrderState StartCooking() => new InKitchen();\n    public override OrderState Cancel() => new Cancelled(); // refund is triggered by an observer\n}\n\npublic sealed class InKitchen : OrderState\n{\n    public override string CustomerMessage => \"We are making your pierogi\";\n    public override OrderState Deliver() => new Delivered();\n}\n\npublic sealed class Delivered : OrderState { public override string CustomerMessage => \"Enjoy your meal\"; }\n\npublic sealed class Cancelled : OrderState { public override string CustomerMessage => \"Order cancelled\"; }\n\npublic sealed class Order(int id)\n{\n    public int Id => id;\n    public OrderState State { get; private set; } = new New();\n\n    public void Pay() => State = State.Pay();\n    public void StartCooking() => State = State.StartCooking();\n    public void Deliver() => State = State.Deliver();\n    public void Cancel() => State = State.Cancel();\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"order.ts"},"content":[{"type":"text","text":"abstract class OrderState {\n  abstract readonly name: string;\n  abstract readonly customerMessage: string;\n\n  // By default every transition is forbidden; states override only what they allow.\n  pay(): OrderState { return this.deny('pay'); }\n  startCooking(): OrderState { return this.deny('start cooking'); }\n  deliver(): OrderState { return this.deny('deliver'); }\n  cancel(): OrderState { return this.deny('cancel'); }\n\n  private deny(action: string): never {\n    throw new Error(`Cannot ${action} an order that is ${this.name}`);\n  }\n}\n\nclass New extends OrderState {\n  readonly name = 'New';\n  readonly customerMessage = 'Waiting for payment';\n  override pay() { return new Paid(); }\n  override cancel() { return new Cancelled(); }\n}\n\nclass Paid extends OrderState {\n  readonly name = 'Paid';\n  readonly customerMessage = 'Payment received';\n  override startCooking() { return new InKitchen(); }\n  override cancel() { return new Cancelled(); }\n}\n\nclass InKitchen extends OrderState {\n  readonly name = 'InKitchen';\n  readonly customerMessage = 'We are making your pierogi';\n  override deliver() { return new Delivered(); }\n}\n\nclass Delivered extends OrderState {\n  readonly name = 'Delivered';\n  readonly customerMessage = 'Enjoy your meal';\n}\n\nclass Cancelled extends OrderState {\n  readonly name = 'Cancelled';\n  readonly customerMessage = 'Order cancelled';\n}\n\nclass Order {\n  private state: OrderState = new New();\n  constructor(readonly id: number) {}\n\n  get status(): string { return this.state.customerMessage; }\n  pay(): void { this.state = this.state.pay(); }\n  startCooking(): void { this.state = this.state.startCooking(); }\n  deliver(): void { this.state = this.state.deliver(); }\n  cancel(): void { this.state = this.state.cancel(); }\n}\n\nconst order = new Order(42);\norder.pay();\norder.startCooking();\nconsole.log(order.status); // We are making your pierogi"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Order.java"},"content":[{"type":"text","text":"abstract class OrderState {\n    String name() { return getClass().getSimpleName(); }\n    abstract String customerMessage();\n\n    // By default every transition is forbidden; states override only what they allow.\n    OrderState pay() { return deny(\"pay\"); }\n    OrderState startCooking() { return deny(\"start cooking\"); }\n    OrderState deliver() { return deny(\"deliver\"); }\n    OrderState cancel() { return deny(\"cancel\"); }\n\n    private OrderState deny(String action) {\n        throw new IllegalStateException(\"Cannot \" + action + \" an order that is \" + name());\n    }\n}\n\nfinal class New extends OrderState {\n    String customerMessage() { return \"Waiting for payment\"; }\n    @Override OrderState pay() { return new Paid(); }\n    @Override OrderState cancel() { return new Cancelled(); }\n}\n\nfinal class Paid extends OrderState {\n    String customerMessage() { return \"Payment received\"; }\n    @Override OrderState startCooking() { return new InKitchen(); }\n    @Override OrderState cancel() { return new Cancelled(); }\n}\n\nfinal class InKitchen extends OrderState {\n    String customerMessage() { return \"We are making your pierogi\"; }\n    @Override OrderState deliver() { return new Delivered(); }\n}\n\nfinal class Delivered extends OrderState { String customerMessage() { return \"Enjoy your meal\"; } }\n\nfinal class Cancelled extends OrderState { String customerMessage() { return \"Order cancelled\"; } }\n\npublic class Order {\n    private OrderState state = new New();\n\n    public void pay() { state = state.pay(); }\n    public void startCooking() { state = state.startCooking(); }\n    public void deliver() { state = state.deliver(); }\n    public void cancel() { state = state.cancel(); }\n    public String status() { return state.customerMessage(); }\n\n    public static void main(String[] args) {\n        var order = new Order();\n        order.pay();\n        order.startCooking();\n        System.out.println(order.status()); // We are making your pierogi\n        try { order.cancel(); } catch (IllegalStateException e) { System.out.println(e.getMessage()); }\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"order.go"},"content":[{"type":"text","text":"package main\n\nimport \"fmt\"\n\ntype OrderState interface {\n\tName() string\n\tCustomerMessage() string\n\tPay() (OrderState, error)\n\tStartCooking() (OrderState, error)\n\tDeliver() (OrderState, error)\n\tCancel() (OrderState, error)\n}\n\n// deny rejects every transition; concrete states embed it and override what they allow.\ntype deny struct{ name, msg string }\n\nfunc (d deny) Name() string            { return d.name }\nfunc (d deny) CustomerMessage() string { return d.msg }\nfunc (d deny) no(action string) (OrderState, error) {\n\treturn nil, fmt.Errorf(\"cannot %s an order that is %s\", action, d.name)\n}\nfunc (d deny) Pay() (OrderState, error)          { return d.no(\"pay\") }\nfunc (d deny) StartCooking() (OrderState, error) { return d.no(\"start cooking\") }\nfunc (d deny) Deliver() (OrderState, error)      { return d.no(\"deliver\") }\nfunc (d deny) Cancel() (OrderState, error)       { return d.no(\"cancel\") }\n\ntype New struct{ deny }\ntype Paid struct{ deny }\ntype InKitchen struct{ deny }\n\nvar (\n\tnewState  = New{deny{\"New\", \"Waiting for payment\"}}\n\tpaid      = Paid{deny{\"Paid\", \"Payment received\"}}\n\tinKitchen = InKitchen{deny{\"InKitchen\", \"We are making your pierogi\"}}\n\tdelivered = deny{\"Delivered\", \"Enjoy your meal\"}\n\tcancelled = deny{\"Cancelled\", \"Order cancelled\"}\n)\n\nfunc (New) Pay() (OrderState, error)           { return paid, nil }\nfunc (New) Cancel() (OrderState, error)        { return cancelled, nil }\nfunc (Paid) StartCooking() (OrderState, error) { return inKitchen, nil }\nfunc (Paid) Cancel() (OrderState, error)       { return cancelled, nil }\nfunc (InKitchen) Deliver() (OrderState, error) { return delivered, nil }\n\ntype Order struct{ State OrderState }\n\n// apply runs a transition and keeps the current state when it is rejected.\nfunc (o *Order) apply(t func() (OrderState, error)) error {\n\tnext, err := t()\n\tif err == nil {\n\t\to.State = next\n\t}\n\treturn err\n}\n\nfunc main() {\n\to := &Order{State: newState}\n\t_ = o.apply(o.State.Pay)\n\t_ = o.apply(o.State.StartCooking)\n\tfmt.Println(o.State.CustomerMessage()) // We are making your pierogi\n\tfmt.Println(o.apply(o.State.Cancel))   // cannot cancel an order that is InKitchen\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"order.py"},"content":[{"type":"text","text":"class OrderState:\n    customer_message = \"\"\n\n    @property\n    def name(self) -> str:\n        return type(self).__name__\n\n    # By default every transition is forbidden; states override only what they allow.\n    def pay(self) -> \"OrderState\": return self._deny(\"pay\")\n    def start_cooking(self) -> \"OrderState\": return self._deny(\"start cooking\")\n    def deliver(self) -> \"OrderState\": return self._deny(\"deliver\")\n    def cancel(self) -> \"OrderState\": return self._deny(\"cancel\")\n\n    def _deny(self, action: str) -> \"OrderState\":\n        raise RuntimeError(f\"Cannot {action} an order that is {self.name}\")\n\n\nclass New(OrderState):\n    customer_message = \"Waiting for payment\"\n    def pay(self): return Paid()\n    def cancel(self): return Cancelled()\n\n\nclass Paid(OrderState):\n    customer_message = \"Payment received\"\n    def start_cooking(self): return InKitchen()\n    def cancel(self): return Cancelled()\n\n\nclass InKitchen(OrderState):\n    customer_message = \"We are making your pierogi\"\n    def deliver(self): return Delivered()\n\n\nclass Delivered(OrderState):\n    customer_message = \"Enjoy your meal\"\n\n\nclass Cancelled(OrderState):\n    customer_message = \"Order cancelled\"\n\n\nclass Order:\n    def __init__(self, order_id: int) -> None:\n        self.id = order_id\n        self.state: OrderState = New()\n\n    def pay(self) -> None: self.state = self.state.pay()\n    def start_cooking(self) -> None: self.state = self.state.start_cooking()\n    def deliver(self) -> None: self.state = self.state.deliver()\n    def cancel(self) -> None: self.state = self.state.cancel()\n\n\norder = Order(42)\norder.pay()\norder.start_cooking()\nprint(order.state.customer_message)  # We are making your pierogi\ntry:\n    order.cancel()\nexcept RuntimeError as e:\n    print(e)  # Cannot cancel an order that is InKitchen"}]}]}]},"toc":[{"id":"problem-ta-sama-drabinka-w-kazdej-metodzie","text":"Problem: ta sama drabinka w każdej metodzie","level":2,"locked":false},{"id":"rozwiazanie-kazdy-etap-to-obiekt","text":"Rozwiązanie: każdy etap to obiekt","level":2,"locked":false},{"id":"implementacja-w-pieciu-jezykach","text":"Implementacja w pięciu językach","level":2,"locked":false},{"id":"krok-po-kroku","text":"Krok po kroku","level":2,"locked":true},{"id":"kiedy-klasa-na-stan-to-za-malo","text":"Kiedy klasa na stan to za mało","level":2,"locked":true},{"id":"stan-a-strategia","text":"Stan a Strategia","level":2,"locked":true},{"id":"kiedy-stosowac-a-kiedy-nie","text":"Kiedy stosować, a kiedy nie","level":2,"locked":true},{"id":"powiazania-z-innymi-wzorcami","text":"Powiązania z innymi wzorcami","level":2,"locked":true},{"id":"w-praktyce","text":"W praktyce","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":39,"visibleBlocks":15,"resources":[{"id":"6b0857bf3c96f2d34d0b428b","type":"article","provider":"web","url":"https://gameprogrammingpatterns.com/state.html","embedUrl":null,"title":"State · Design Patterns Revisited · Game Programming Patterns","description":"","author":"Robert Nystrom","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["state"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:26:37.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T23:13:50.442Z"},{"id":"6b0857c83c96f2d34d0b4a41","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=26xrX113KZc","embedUrl":"https://www.youtube-nocookie.com/embed/26xrX113KZc","title":"Mauro Servienti - Talk Session: Welcome to the (State) Machine","description":"Explore DDD 2019 - Denver, Sept. 16-20 Stateless all the things, they say. In the last few years we've been brainwashed: design stateless systems, otherwise they cannot scale, they cannot be highly available, and they are hard to maintain and evolve. In a nutshell stateful is bad. However complex…","author":"Explore DDD","thumbnailUrl":"https://i.ytimg.com/vi/26xrX113KZc/hqdefault.jpg","durationSec":null,"lang":"en","topics":["ddd-strategic-design"],"techs":["general"],"tags":["software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2019-10-05T18:52:49.000Z","popularity":57,"verifiedAt":"2026-11-26T10:53:11.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857bf3c96f2d34d0b428a","type":"article","provider":"web","url":"https://refactoring.guru/pl/design-patterns/state","embedUrl":null,"title":"Stan / State","description":"Stan to behawioralny wzorzec projektowy pozwalający obiektowi zmienić swoje zachowanie gdy zmieni się jego stan wewnętrzny. Wygląda to tak, jakby obiekt zmienił swoją klasę.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/pl/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"pl","topics":["state"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:26:13.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c33c96f2d34d0b4666","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL16942701W","embedUrl":null,"title":"Head First design patterns","description":"","author":"Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates","thumbnailUrl":"https://covers.openlibrary.org/b/id/388950-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["java"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2004-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"}],"challenges":[{"id":"6b093dc291bd8fbaf2a0c8e4","slug":"subscription-state","title":"Cykl życia subskrypcji jako maszyna stanów","summary":"Subskrypcja SaaS przechodzi przez okres próbny, aktywność, zaległość i anulowanie. Każdy stan to osobna klasa, która sama decyduje o przejściach – bez rozrastającego się switcha.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["state"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["state","state-machine","subscriptions","billing","behavioral"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.723Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-behavioral","title":"Wzorce behawioralne GoF","items":[{"slug":"strategy","title":"Strategia (Strategy): wymienne algorytmy zamiast drabinki if-ów","current":false},{"slug":"observer","title":"Obserwator (Observer): powiadom wszystkich, nie znając nikogo","current":false},{"slug":"command","title":"Polecenie (Command): żądanie zamknięte w obiekcie","current":false},{"slug":"state","title":"Stan (State): obiekt, który zmienia zachowanie razem z etapem życia","current":true},{"slug":"template-method","title":"Metoda szablonowa (Template Method): stały przepis, wymienne składniki","current":false},{"slug":"iterator","title":"Iterator: przechodzenie po kolekcji bez zaglądania do środka","current":false},{"slug":"chain-of-responsibility","title":"Łańcuch zobowiązań (Chain of Responsibility): podaj dalej, aż ktoś się zajmie","current":false},{"slug":"mediator","title":"Mediator: komponenty rozmawiają przez koordynatora","current":false},{"slug":"memento","title":"Pamiątka (Memento): migawka stanu bez łamania hermetyzacji","current":false},{"slug":"visitor","title":"Odwiedzający (Visitor): nowe operacje bez zmiany klas","current":false}]}],"prev":{"slug":"command","title":"Polecenie (Command): żądanie zamknięte w obiekcie"},"next":{"slug":"template-method","title":"Metoda szablonowa (Template Method): stały przepis, wymienne składniki"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}