{"id":"6b08bd3e80884893657cca24","slug":"template-method","title":"Metoda szablonowa (Template Method): stały przepis, wymienne składniki","summary":"Wzorzec Metoda szablonowa na przykładzie importu cenników z hurtowni: klasa bazowa ustala kolejność kroków, a podklasy dostarczają parsowanie i opcjonalne haki. Zasada Hollywood, wariant bez dziedziczenia w Go i kod w pięciu językach.","servedLang":"pl","availableLangs":["pl","en"],"topics":["template-method"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","behavioral","template-method","inheritance","hooks"],"level":"beginner","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":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:06.512Z","updatedAt":"2026-11-27T10:04:58.495Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"violet","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"Wzorzec projektowy Metoda szablonowa (Template Method) w C#, TypeScript, Java, Go i Python: szkielet algorytmu, kroki abstrakcyjne, haki i porównanie ze Strategią.","wordCount":2342,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Każdy rodzaj pierogów Haliny powstaje według tego samego przepisu: ciasto, farsz, lepienie, gotowanie, czasem jeszcze podsmażanie. Zmienia się farsz, kolejność nigdy. "},{"type":"text","text":"Metoda szablonowa","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"Template Method","marks":[{"type":"italic"}]},{"type":"text","text":") zapisuje taki przepis w klasie bazowej, a podklasom zostawia tylko te kroki, które naprawdę się różnią. W kodzie pierogarni ten przepis to import cenników od dostawców."}]},{"type":"callout","attrs":{"variant":"tip","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Klasa bazowa definiuje "},{"type":"text","text":"metodę szablonową","marks":[{"type":"bold"}]},{"type":"text","text":" – stałą sekwencję kroków algorytmu."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Podklasy implementują "},{"type":"text","text":"kroki abstrakcyjne","marks":[{"type":"bold"}]},{"type":"text","text":" (wymagane) i mogą nadpisać "},{"type":"text","text":"haki","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"hooks","marks":[{"type":"italic"}]},{"type":"text","text":") z domyślnym zachowaniem."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Sterowanie jest odwrócone: to klasa bazowa woła podklasę, nie odwrotnie („nie dzwoń do nas, my zadzwonimy do ciebie”)."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"1","label":"metoda ustala kolejność","hint":"run() – wspólna dla wszystkich importów"},{"value":"1","label":"krok wymagany","hint":"parse() – każda hurtownia ma inny format"},{"value":"1","label":"hak opcjonalny","hint":"adjust() – np. dopłata za chłodzenie"}]}},{"type":"heading","attrs":{"level":2,"id":"problem-dwa-importy-jedna-logika-dwie-kopie"},"content":[{"type":"text","text":"Problem: dwa importy, jedna logika, dwie kopie"}]},{"type":"paragraph","content":[{"type":"text","text":"Gospodarstwo przysyła ceny w CSV, mleczarnia – w JSON. Pierwsze wersje importów powstały metodą „kopiuj i popraw”:"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"imports_before.py"},"content":[{"type":"text","text":"def import_farm_csv(raw: str) -> int:\n    items = [line.split(\";\") for line in raw.splitlines() if line]\n    valid = [i for i in items if i[0] and float(i[2].replace(\",\", \".\")) > 0]\n    db.save_prices(valid)\n    return len(valid)\n\n\ndef import_dairy_json(raw: str) -> int:\n    items = json.loads(raw)\n    valid = [i for i in items if i[\"name\"]]  # someone forgot the price check here\n    for i in valid:\n        i[\"price\"] = round(i[\"price\"] * 1.02, 2)  # cooling fee\n    db.save_prices(valid)\n    return len(valid)"}]},{"type":"paragraph","content":[{"type":"text","text":"Obie funkcje robią to samo: parsują, walidują, poprawiają i zapisują. Różni się tylko pierwszy krok i dopłata mleczarni. Skopiowana walidacja już się rozjechała – w imporcie z mleczarni ktoś zgubił sprawdzanie ceny, więc ser za 0 zł trafiłby do bazy. Trzeci dostawca oznaczałby trzecią kopię i trzecie miejsce, w którym można zapomnieć o regule."}]},{"type":"heading","attrs":{"level":2,"id":"rozwiazanie-szkielet-w-klasie-bazowej"},"content":[{"type":"text","text":"Rozwiązanie: szkielet w klasie bazowej"}]},{"type":"paragraph","content":[{"type":"text","text":"Wspólny przebieg trafia do klasy bazowej jako metoda "},{"type":"text","text":"run()","marks":[{"type":"code"}]},{"type":"text","text":". Metoda woła po kolei kroki: "},{"type":"text","text":"parse()","marks":[{"type":"code"}]},{"type":"text","text":" jest abstrakcyjny, więc każda podklasa musi go dostarczyć; "},{"type":"text","text":"isValid()","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"save()","marks":[{"type":"code"}]},{"type":"text","text":" są prywatne i wspólne; "},{"type":"text","text":"adjust()","marks":[{"type":"code"}]},{"type":"text","text":" to "},{"type":"text","text":"hak","marks":[{"type":"bold"}]},{"type":"text","text":" – ma domyślną implementację „nic nie zmieniaj”, ale podklasa może go nadpisać."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant C as Klient\n  participant B as PriceListImport (baza)\n  participant D as DairyJsonImport (podklasa)\n  C->>B: run(raw)\n  B->>D: parse(raw)\n  D-->>B: lista pozycji\n  B->>B: isValid() – wspólna walidacja\n  B->>D: adjust(item) – hak\n  D-->>B: cena + 2%\n  B->>B: save(valid)\n  B-->>C: raport: 1 zaimportowana, 0 odrzuconych","caption":"Kto kogo woła: zasada Hollywood"}},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  class PriceListImport {\n    <<abstract>>\n    +run(raw) ImportReport\n    #parse(raw) List~PriceItem~*\n    #adjust(item) PriceItem\n    -isValid(item) bool\n    -save(items)\n  }\n  PriceListImport <|-- FarmCsvImport\n  PriceListImport <|-- DairyJsonImport\n  class FarmCsvImport {\n    #parse(raw) List~PriceItem~\n  }\n  class DairyJsonImport {\n    #parse(raw) List~PriceItem~\n    #adjust(item) PriceItem\n  }","caption":"Struktura wzorca Metoda szablonowa"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Element"}]}]},{"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":"Kto go definiuje"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Metoda szablonowa"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"run()","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"klasa bazowa; nie do nadpisania ("},{"type":"text","text":"final","marks":[{"type":"code"}]},{"type":"text","text":", niewirtualna)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Krok abstrakcyjny"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"parse()","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"każda podklasa obowiązkowo"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Hak ("},{"type":"text","text":"hook","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"adjust()","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"klasa bazowa (domyślnie), podklasa opcjonalnie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Krok wspólny"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"isValid()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"save()","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"klasa bazowa, prywatnie"}]}]}]}]},{"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":"C#, TypeScript, Java i Python realizują wzorzec klasycznie – przez klasę abstrakcyjną. W Javie metoda szablonowa jest "},{"type":"text","text":"final","marks":[{"type":"code"}]},{"type":"text","text":", w C# po prostu nie jest wirtualna. Go nie ma dziedziczenia, więc szkielet jest "},{"type":"text","text":"funkcją","marks":[{"type":"bold"}]},{"type":"text","text":" przyjmującą interfejs z wymaganym krokiem, a hak wykrywa się asercją typu: jeśli parser implementuje też "},{"type":"text","text":"Adjuster","marks":[{"type":"code"}]},{"type":"text","text":", funkcja go użyje."}]},{"type":"codeGroup","attrs":{"title":"Metoda szablonowa – import cenników"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"PriceListImport.cs"},"content":[{"type":"text","text":"using System.Globalization;\nusing System.Text.Json;\n\nConsole.WriteLine(new FarmCsvImport().Run(\"cheese;kg;24,50\\npotatoes;kg;3,20\\nonions;kg;-1\"));\nConsole.WriteLine(new DairyJsonImport().Run(\"\"\"[{\"name\":\"cream\",\"unit\":\"l\",\"price\":12.0}]\"\"\"));\n\npublic sealed record PriceItem(string Name, string Unit, decimal Price);\npublic sealed record ImportReport(int Imported, int Rejected);\n\npublic abstract class PriceListImport\n{\n    // The template method: a fixed sequence of steps, deliberately not virtual.\n    public ImportReport Run(string raw)\n    {\n        var items = Parse(raw).ToList();\n        var valid = items.Where(IsValid).Select(Adjust).ToList();\n        Save(valid);\n        return new ImportReport(valid.Count, items.Count - valid.Count);\n    }\n\n    protected abstract IEnumerable<PriceItem> Parse(string raw); // required step\n\n    protected virtual PriceItem Adjust(PriceItem item) => item; // optional hook\n\n    private static bool IsValid(PriceItem i) => i.Name.Length > 0 && i.Price > 0;\n\n    private void Save(List<PriceItem> items) =>\n        items.ForEach(i => Console.WriteLine($\"{GetType().Name}: {i.Name} = {i.Price:0.00} PLN/{i.Unit}\"));\n}\n\npublic sealed class FarmCsvImport : PriceListImport\n{\n    protected override IEnumerable<PriceItem> Parse(string raw) =>\n        raw.Split('\\n', StringSplitOptions.RemoveEmptyEntries)\n           .Select(line => line.Split(';'))\n           .Select(c => new PriceItem(c[0], c[1], decimal.Parse(c[2].Replace(',', '.'), CultureInfo.InvariantCulture)));\n}\n\npublic sealed class DairyJsonImport : PriceListImport\n{\n    private static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web);\n\n    protected override IEnumerable<PriceItem> Parse(string raw) =>\n        JsonSerializer.Deserialize<List<PriceItem>>(raw, Options) ?? [];\n\n    // The dairy adds a 2% cooling fee to every price.\n    protected override PriceItem Adjust(PriceItem item) => item with { Price = Math.Round(item.Price * 1.02m, 2) };\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"price-list-import.ts"},"content":[{"type":"text","text":"type PriceItem = { name: string; unit: string; price: number };\ntype ImportReport = { imported: number; rejected: number };\n\nabstract class PriceListImport {\n  // The template method: subclasses fill in steps but never change their order.\n  run(raw: string): ImportReport {\n    const items = this.parse(raw);\n    const valid = items.filter((i) => this.isValid(i)).map((i) => this.adjust(i));\n    this.save(valid);\n    return { imported: valid.length, rejected: items.length - valid.length };\n  }\n\n  protected abstract parse(raw: string): PriceItem[]; // required step\n\n  protected adjust(item: PriceItem): PriceItem { return item; } // optional hook\n\n  private isValid(i: PriceItem): boolean { return i.name.length > 0 && i.price > 0; }\n\n  private save(items: PriceItem[]): void {\n    for (const i of items) console.log(`${this.constructor.name}: ${i.name} = ${i.price.toFixed(2)} PLN/${i.unit}`);\n  }\n}\n\nclass FarmCsvImport extends PriceListImport {\n  protected parse(raw: string): PriceItem[] {\n    return raw.split('\\n').filter(Boolean).map((line) => {\n      const [name, unit, price] = line.split(';');\n      return { name, unit, price: Number(price.replace(',', '.')) };\n    });\n  }\n}\n\nclass DairyJsonImport extends PriceListImport {\n  protected parse(raw: string): PriceItem[] {\n    return JSON.parse(raw) as PriceItem[];\n  }\n\n  // The dairy adds a 2% cooling fee to every price.\n  protected override adjust(item: PriceItem): PriceItem {\n    return { ...item, price: Math.round(item.price * 102) / 100 };\n  }\n}\n\nconsole.log(new FarmCsvImport().run('cheese;kg;24,50\\npotatoes;kg;3,20\\nonions;kg;-1')); // imported 2, rejected 1\nconsole.log(new DairyJsonImport().run('[{\"name\":\"cream\",\"unit\":\"l\",\"price\":12}]'));      // cream = 12.24"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"PriceListImport.java"},"content":[{"type":"text","text":"import java.util.Arrays;\nimport java.util.List;\nimport java.util.regex.Pattern;\n\nrecord PriceItem(String name, String unit, double price) {}\nrecord ImportReport(int imported, int rejected) {}\n\npublic abstract class PriceListImport {\n    // The template method: final, so subclasses cannot change the order of steps.\n    public final ImportReport run(String raw) {\n        List<PriceItem> items = parse(raw);\n        List<PriceItem> valid = items.stream().filter(this::isValid).map(this::adjust).toList();\n        save(valid);\n        return new ImportReport(valid.size(), items.size() - valid.size());\n    }\n\n    protected abstract List<PriceItem> parse(String raw); // required step\n\n    protected PriceItem adjust(PriceItem item) { return item; } // optional hook\n\n    private boolean isValid(PriceItem i) { return !i.name().isBlank() && i.price() > 0; }\n\n    private void save(List<PriceItem> items) {\n        items.forEach(i -> System.out.printf(\"%s: %s = %.2f PLN/%s%n\", getClass().getSimpleName(), i.name(), i.price(), i.unit()));\n    }\n\n    public static void main(String[] args) {\n        System.out.println(new FarmCsvImport().run(\"cheese;kg;24,50\\npotatoes;kg;3,20\\nonions;kg;-1\"));\n        System.out.println(new DairyLineImport().run(\"cream|l|12.00\"));\n    }\n}\n\nclass FarmCsvImport extends PriceListImport {\n    @Override protected List<PriceItem> parse(String raw) {\n        return raw.lines().filter(l -> !l.isBlank()).map(l -> l.split(\";\"))\n            .map(c -> new PriceItem(c[0], c[1], Double.parseDouble(c[2].replace(',', '.')))).toList();\n    }\n}\n\nclass DairyLineImport extends PriceListImport {\n    private static final Pattern SEP = Pattern.compile(\"\\\\|\");\n\n    @Override protected List<PriceItem> parse(String raw) {\n        return raw.lines().map(SEP::split).map(c -> new PriceItem(c[0], c[1], Double.parseDouble(c[2]))).toList();\n    }\n\n    // The dairy adds a 2% cooling fee to every price.\n    @Override protected PriceItem adjust(PriceItem i) {\n        return new PriceItem(i.name(), i.unit(), Math.round(i.price() * 102) / 100.0);\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"import.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype PriceItem struct {\n\tName  string  `json:\"name\"`\n\tUnit  string  `json:\"unit\"`\n\tPrice float64 `json:\"price\"`\n}\n\n// Parser is the required step; Adjuster is an optional hook detected at runtime.\ntype Parser interface{ Parse(raw string) ([]PriceItem, error) }\ntype Adjuster interface{ Adjust(PriceItem) PriceItem }\n\n// Run is the template: Go has no inheritance, so the skeleton is a function over an interface.\nfunc Run(p Parser, raw string) (imported, rejected int, err error) {\n\titems, err := p.Parse(raw)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tfor _, it := range items {\n\t\tif it.Name == \"\" || it.Price <= 0 {\n\t\t\trejected++\n\t\t\tcontinue\n\t\t}\n\t\tif a, ok := p.(Adjuster); ok {\n\t\t\tit = a.Adjust(it)\n\t\t}\n\t\tfmt.Printf(\"%T: %s = %.2f PLN/%s\\n\", p, it.Name, it.Price, it.Unit) // save\n\t\timported++\n\t}\n\treturn imported, rejected, nil\n}\n\ntype FarmCSV struct{}\n\nfunc (FarmCSV) Parse(raw string) ([]PriceItem, error) {\n\tvar out []PriceItem\n\tfor _, line := range strings.Fields(raw) {\n\t\tc := strings.Split(line, \";\")\n\t\tprice, err := strconv.ParseFloat(strings.Replace(c[2], \",\", \".\", 1), 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout = append(out, PriceItem{c[0], c[1], price})\n\t}\n\treturn out, nil\n}\n\ntype DairyJSON struct{}\n\nfunc (DairyJSON) Parse(raw string) (items []PriceItem, err error) {\n\terr = json.Unmarshal([]byte(raw), &items)\n\treturn items, err\n}\n\n// Adjust adds the dairy's 2% cooling fee.\nfunc (DairyJSON) Adjust(i PriceItem) PriceItem {\n\ti.Price = math.Round(i.Price*102) / 100\n\treturn i\n}\n\nfunc main() {\n\tfmt.Println(Run(FarmCSV{}, \"cheese;kg;24,50\\npotatoes;kg;3,20\\nonions;kg;-1\"))\n\tfmt.Println(Run(DairyJSON{}, `[{\"name\":\"cream\",\"unit\":\"l\",\"price\":12}]`))\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"price_list_import.py"},"content":[{"type":"text","text":"import json\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, replace\n\n\n@dataclass(frozen=True)\nclass PriceItem:\n    name: str\n    unit: str\n    price: float\n\n\nclass PriceListImport(ABC):\n    def run(self, raw: str) -> tuple[int, int]:\n        \"\"\"The template method: subclasses fill in steps, never the order.\"\"\"\n        items = self.parse(raw)\n        valid = [self.adjust(i) for i in items if self._is_valid(i)]\n        self._save(valid)\n        return len(valid), len(items) - len(valid)\n\n    @abstractmethod\n    def parse(self, raw: str) -> list[PriceItem]:\n        \"\"\"Required step.\"\"\"\n\n    def adjust(self, item: PriceItem) -> PriceItem:\n        \"\"\"Optional hook – returns the item unchanged by default.\"\"\"\n        return item\n\n    @staticmethod\n    def _is_valid(item: PriceItem) -> bool:\n        return bool(item.name) and item.price > 0\n\n    def _save(self, items: list[PriceItem]) -> None:\n        for i in items:\n            print(f\"{type(self).__name__}: {i.name} = {i.price:.2f} PLN/{i.unit}\")\n\n\nclass FarmCsvImport(PriceListImport):\n    def parse(self, raw: str) -> list[PriceItem]:\n        rows = (line.split(\";\") for line in raw.splitlines() if line)\n        return [PriceItem(name, unit, float(price.replace(\",\", \".\"))) for name, unit, price in rows]\n\n\nclass DairyJsonImport(PriceListImport):\n    def parse(self, raw: str) -> list[PriceItem]:\n        return [PriceItem(**row) for row in json.loads(raw)]\n\n    def adjust(self, item: PriceItem) -> PriceItem:\n        return replace(item, price=round(item.price * 1.02, 2))  # 2% cooling fee\n\n\nprint(FarmCsvImport().run(\"cheese;kg;24,50\\npotatoes;kg;3,20\\nonions;kg;-1\"))  # (2, 1)\nprint(DairyJsonImport().run('[{\"name\": \"cream\", \"unit\": \"l\", \"price\": 12.0}]'))  # (1, 0)"}]}]}]},"toc":[{"id":"problem-dwa-importy-jedna-logika-dwie-kopie","text":"Problem: dwa importy, jedna logika, dwie kopie","level":2,"locked":false},{"id":"rozwiazanie-szkielet-w-klasie-bazowej","text":"Rozwiązanie: szkielet w klasie bazowej","level":2,"locked":false},{"id":"implementacja-w-pieciu-jezykach","text":"Implementacja w pięciu językach","level":2,"locked":false},{"id":"szablon-bez-dziedziczenia","text":"Szablon bez dziedziczenia","level":2,"locked":true},{"id":"krok-po-kroku","text":"Krok po kroku","level":2,"locked":true},{"id":"metoda-szablonowa-a-strategia","text":"Metoda szablonowa 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":36,"visibleBlocks":15,"resources":[{"id":"6b0857bf3c96f2d34d0b42cd","type":"article","provider":"web","url":"https://refactoring.guru/pl/design-patterns/template-method","embedUrl":null,"title":"Metoda szablonowa / Template Method","description":"Metoda szablonowa to behawioralny wzorzec projektowy definiujący szkielet algorytmu w klasie bazowej, ale pozwalający podklasom nadpisać pewne etapy tego algorytmu bez konieczności zmiany jego struktury.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/pl/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"pl","topics":["template-method"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":60,"verifiedAt":"2026-11-26T11:26:14.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"},{"id":"6b0857be3c96f2d34d0b4233","type":"article","provider":"web","url":"https://java-design-patterns.com/patterns","embedUrl":null,"title":"Design Pattern Catalog","description":"Discover the full list of Java design patterns. This comprehensive guide provides you with all the information you need to master pattern implementation in your Java applications.","author":"Java Design Patterns","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":[],"techs":["java"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":70,"verifiedAt":"2026-11-26T11:26:34.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857c33c96f2d34d0b4658","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6030812W","embedUrl":null,"title":"Design Patterns: Elements of Reusable Object-Oriented Software","description":"","author":"Erich Gamma, John Vlissides, Richard Helm, Ralph Johnson","thumbnailUrl":"https://covers.openlibrary.org/b/id/6601119-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":["general"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"1995-01-01T00:00:00.000Z","popularity":71,"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":[],"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":false},{"slug":"template-method","title":"Metoda szablonowa (Template Method): stały przepis, wymienne składniki","current":true},{"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":"state","title":"Stan (State): obiekt, który zmienia zachowanie razem z etapem życia"},"next":{"slug":"iterator","title":"Iterator: przechodzenie po kolekcji bez zaglądania do środka"},"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}]}}