{"id":"6b08bd3d80884893657cc9fb","slug":"proxy","title":"Pełnomocnik (Proxy) – zastępca, który kontroluje dostęp do prawdziwego obiektu","summary":"Pełnomocnik ma ten sam interfejs co prawdziwy obiekt i stoi przed nim, decydując, kiedy i czy w ogóle przekazać wywołanie. Przykład archiwum faktur z kontrolą uprawnień i leniwym połączeniem w C#, TypeScript, Javie, Go i Pythonie.","servedLang":"pl","availableLangs":["pl","en"],"topics":["proxy","decorator","adapter","facade"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","structural","proxy","lazy-loading","access-control"],"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":10,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:05.076Z","updatedAt":"2026-11-27T10:04:59.090Z","requestedLang":"pl","theme":{"hero":"minimal","heroMedia":null,"accent":"indigo","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"Wzorzec Pełnomocnik (Proxy) – pełnomocnik wirtualny, ochronny, zdalny i buforujący, diagramy, kod w C#, TypeScript, Java, Go i Python, proxy w EF Core, Spring AOP, JavaScript Proxy, weakref.proxy i pułapka samowywołania.","wordCount":1972,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Czasem nie chcesz, żeby klient rozmawiał z obiektem bezpośrednio: obiekt jest drogi w utworzeniu, leży na innym serwerze albo nie każdy powinien mieć do niego dostęp. "},{"type":"text","text":"Pełnomocnik","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"Proxy","marks":[{"type":"italic"}]},{"type":"text","text":") to zastępca o identycznym interfejsie. Klient nie widzi różnicy, a pełnomocnik może sprawdzić uprawnienia, utworzyć prawdziwy obiekt dopiero przy pierwszym użyciu, zbuforować wynik albo przesłać wywołanie przez sieć."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Pełnomocnik implementuje ten sam interfejs co prawdziwy obiekt ("},{"type":"text","text":"real subject","marks":[{"type":"italic"}]},{"type":"text","text":") i trzyma do niego referencję – albo przepis, jak go utworzyć."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Decyduje, "},{"type":"text","text":"czy","marks":[{"type":"italic"}]},{"type":"text","text":" i "},{"type":"text","text":"kiedy","marks":[{"type":"italic"}]},{"type":"text","text":" przekazać wywołanie: kontrola dostępu, leniwe tworzenie, cache, zdalność."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Klient nie musi wiedzieć, czy rozmawia z pełnomocnikiem, czy z oryginałem."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"problem-archiwum-faktur-dla-wszystkich-i-od-razu"},"content":[{"type":"text","text":"Problem: archiwum faktur dla wszystkich i od razu"}]},{"type":"paragraph","content":[{"type":"text","text":"Platforma kursów przechowuje faktury w PDF w chmurowym magazynie plików. Klasa "},{"type":"text","text":"CloudInvoiceArchive","marks":[{"type":"code"}]},{"type":"text","text":" przy tworzeniu otwiera połączenie i uwierzytelnia się, co trwa kilkaset milisekund. Kod wyglądał tak:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"invoices-controller.ts"},"content":[{"type":"text","text":"const archive = new CloudInvoiceArchive(); // connects on every request, even if unused\n\napp.get(\"/invoices/:path(*)\", async (req, res) => {\n  // every developer has to remember this check – and one endpoint forgot it\n  if (!req.user.isAccountant && !req.params.path.startsWith(`${req.user.name}/`)) {\n    return res.status(403).end();\n  }\n  res.send(await archive.fetch(req.params.path));\n});"}]},{"type":"paragraph","content":[{"type":"text","text":"Sprawdzanie uprawnień jest rozsiane po kontrolerach i w jednym z nich ktoś je pominął – student mógł pobrać cudzą fakturę, zgadując ścieżkę. A połączenie z magazynem powstaje nawet wtedy, gdy żądanie i tak zostanie odrzucone."}]},{"type":"heading","attrs":{"level":2,"id":"rozwiazanie-zastepca-o-tym-samym-interfejsie"},"content":[{"type":"text","text":"Rozwiązanie: zastępca o tym samym interfejsie"}]},{"type":"paragraph","content":[{"type":"text","text":"Tworzymy "},{"type":"text","text":"SecuredInvoiceArchive","marks":[{"type":"code"}]},{"type":"text","text":", który implementuje ten sam interfejs "},{"type":"text","text":"InvoiceArchive","marks":[{"type":"code"}]},{"type":"text","text":". Pełnomocnik zna bieżącego użytkownika i funkcję tworzącą prawdziwe archiwum. Przy każdym "},{"type":"text","text":"fetch()","marks":[{"type":"code"}]},{"type":"text","text":" najpierw sprawdza uprawnienia, a prawdziwe archiwum tworzy dopiero przy pierwszym dozwolonym wywołaniu. Kontrolery dostają pełnomocnika i nie muszą pamiętać o niczym."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class InvoiceArchive {\n    <<interface>>\n    +fetch(path) bytes\n  }\n  class CloudInvoiceArchive {\n    +fetch(path) bytes\n  }\n  class SecuredInvoiceArchive {\n    -user User\n    -createReal()\n    -real InvoiceArchive\n    +fetch(path) bytes\n  }\n  InvoiceArchive <|.. CloudInvoiceArchive\n  InvoiceArchive <|.. SecuredInvoiceArchive\n  SecuredInvoiceArchive --> CloudInvoiceArchive : tworzy leniwie i deleguje\n  InvoicesController --> InvoiceArchive","caption":"Pełnomocnik ma ten sam interfejs co prawdziwy obiekt i zarządza jego utworzeniem"}},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant K as Kontroler\n  participant P as SecuredInvoiceArchive\n  participant R as CloudInvoiceArchive\n  K->>P: fetch(\"jan/2026-11.pdf\")\n  P-->>K: odmowa – ola nie jest właścicielką\n  K->>P: fetch(\"ola/2026-11.pdf\")\n  P->>R: utwórz (połączenie z magazynem)\n  P->>R: fetch(\"ola/2026-11.pdf\")\n  R-->>P: PDF\n  P-->>K: PDF","caption":"Odmowa nie otwiera połączenia; pierwsze dozwolone wywołanie tworzy prawdziwe archiwum"}},{"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":"Podmiot ("},{"type":"text","text":"Subject","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"InvoiceArchive","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wspólny interfejs oryginału i pełnomocnika"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Prawdziwy podmiot ("},{"type":"text","text":"Real Subject","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"CloudInvoiceArchive","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"właściwa praca – pobranie pliku z magazynu"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Pełnomocnik ("},{"type":"text","text":"Proxy","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"SecuredInvoiceArchive","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kontrola dostępu i leniwe utworzenie oryginału"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Klient"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kontroler faktur"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"korzysta z interfejsu, nie wie o pełnomocniku"}]}]}]}]},{"type":"heading","attrs":{"level":3,"id":"rodzaje-pelnomocnikow"},"content":[{"type":"text","text":"Rodzaje pełnomocników"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Rodzaj"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Co robi"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przykład z życia"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wirtualny ("},{"type":"text","text":"virtual","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tworzy kosztowny obiekt dopiero przy pierwszym użyciu"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"leniwe ładowanie encji w ORM"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Ochronny ("},{"type":"text","text":"protection","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"sprawdza uprawnienia przed delegacją"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nasze archiwum faktur"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Zdalny ("},{"type":"text","text":"remote","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ukrywa komunikację sieciową za lokalnym interfejsem"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"klient wygenerowany z gRPC lub OpenAPI"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Buforujący ("},{"type":"text","text":"caching","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zwraca zapamiętany wynik zamiast pytać oryginał"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cache odpowiedzi drogiego API"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Rejestrujący ("},{"type":"text","text":"smart reference","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"liczy referencje, loguje, mierzy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"liczniki wywołań, audyt dostępu"}]}]}]}]},{"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":"Przykład łączy dwa rodzaje: ochronny i wirtualny. Zwróć uwagę na wynik – odmowa dostępu nie otwiera połączenia, które powstaje dopiero przy pierwszym dozwolonym wywołaniu. Leniwe tworzenie jest bezpieczne wątkowo dzięki "},{"type":"text","text":"Lazy<T>","marks":[{"type":"code"}]},{"type":"text","text":" w C#, metodzie "},{"type":"text","text":"synchronized","marks":[{"type":"code"}]},{"type":"text","text":" w Javie i "},{"type":"text","text":"sync.OnceValue","marks":[{"type":"code"}]},{"type":"text","text":" w Go; w Pythonie posłużył "},{"type":"text","text":"functools.cached_property","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"codeGroup","attrs":{"title":"SecuredInvoiceArchive"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Invoices.cs"},"content":[{"type":"text","text":"var ola = new User(\"ola\", IsAccountant: false);\nIInvoiceArchive archive = new SecuredInvoiceArchive(() => new CloudInvoiceArchive(), ola);\n\ntry { archive.Fetch(\"jan/2026-11.pdf\"); } // denied before any connection is opened\ncatch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); }\n\nConsole.WriteLine($\"{archive.Fetch(\"ola/2026-11.pdf\").Length} bytes\"); // connects now\n\npublic sealed record User(string Name, bool IsAccountant);\n\npublic interface IInvoiceArchive\n{\n    byte[] Fetch(string path);\n}\n\n// Real subject: expensive to create (opens a connection) and to call.\npublic sealed class CloudInvoiceArchive : IInvoiceArchive\n{\n    public CloudInvoiceArchive() => Console.WriteLine(\"connecting to cloud storage...\");\n\n    public byte[] Fetch(string path) => new byte[1024]; // pretend this is a PDF\n}\n\n// Proxy: same interface; checks access and creates the real archive only when needed.\npublic sealed class SecuredInvoiceArchive(Func<IInvoiceArchive> createReal, User user) : IInvoiceArchive\n{\n    private readonly Lazy<IInvoiceArchive> _real = new(createReal); // thread-safe lazy creation\n\n    public byte[] Fetch(string path)\n    {\n        if (!user.IsAccountant && !path.StartsWith($\"{user.Name}/\", StringComparison.Ordinal))\n            throw new UnauthorizedAccessException($\"{user.Name} cannot read {path}\");\n        return _real.Value.Fetch(path);\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"invoices.ts"},"content":[{"type":"text","text":"interface User {\n  name: string;\n  isAccountant: boolean;\n}\n\ninterface InvoiceArchive {\n  fetch(path: string): Promise<Uint8Array>;\n}\n\n// Real subject: expensive to create (opens a connection) and to call.\nclass CloudInvoiceArchive implements InvoiceArchive {\n  constructor() {\n    console.log(\"connecting to cloud storage...\");\n  }\n\n  async fetch(path: string): Promise<Uint8Array> {\n    return new Uint8Array(1024); // pretend this is a PDF\n  }\n}\n\n// Proxy: same interface; checks access and creates the real archive only when needed.\nclass SecuredInvoiceArchive implements InvoiceArchive {\n  private real?: InvoiceArchive;\n\n  constructor(private readonly createReal: () => InvoiceArchive, private readonly user: User) {}\n\n  async fetch(path: string): Promise<Uint8Array> {\n    if (!this.user.isAccountant && !path.startsWith(`${this.user.name}/`)) {\n      throw new Error(`${this.user.name} cannot read ${path}`);\n    }\n    this.real ??= this.createReal(); // virtual proxy: connect on first allowed call\n    return this.real.fetch(path);\n  }\n}\n\nconst archive: InvoiceArchive = new SecuredInvoiceArchive(() => new CloudInvoiceArchive(), {\n  name: \"ola\",\n  isAccountant: false,\n});\n\narchive\n  .fetch(\"jan/2026-11.pdf\")\n  .catch((e: Error) => console.log(e.message)) // denied before any connection is opened\n  .then(() => archive.fetch(\"ola/2026-11.pdf\"))\n  .then((pdf) => console.log(`${pdf.length} bytes`));"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Invoices.java"},"content":[{"type":"text","text":"import java.util.function.Supplier;\n\nrecord User(String name, boolean isAccountant) {}\n\ninterface InvoiceArchive {\n    byte[] fetch(String path);\n}\n\n// Real subject: expensive to create (opens a connection) and to call.\nclass CloudInvoiceArchive implements InvoiceArchive {\n    CloudInvoiceArchive() { System.out.println(\"connecting to cloud storage...\"); }\n    public byte[] fetch(String path) { return new byte[1024]; } // pretend this is a PDF\n}\n\n// Proxy: same interface; checks access and creates the real archive only when needed.\nfinal class SecuredInvoiceArchive implements InvoiceArchive {\n    private final Supplier<InvoiceArchive> createReal;\n    private final User user;\n    private InvoiceArchive real;\n\n    SecuredInvoiceArchive(Supplier<InvoiceArchive> createReal, User user) {\n        this.createReal = createReal;\n        this.user = user;\n    }\n\n    public byte[] fetch(String path) {\n        if (!user.isAccountant() && !path.startsWith(user.name() + \"/\"))\n            throw new SecurityException(user.name() + \" cannot read \" + path);\n        return realArchive().fetch(path);\n    }\n\n    private synchronized InvoiceArchive realArchive() {\n        if (real == null) real = createReal.get(); // virtual proxy: connect on first allowed call\n        return real;\n    }\n}\n\npublic class Invoices {\n    public static void main(String[] args) {\n        InvoiceArchive archive = new SecuredInvoiceArchive(CloudInvoiceArchive::new, new User(\"ola\", false));\n        try {\n            archive.fetch(\"jan/2026-11.pdf\"); // denied before any connection is opened\n        } catch (SecurityException e) {\n            System.out.println(e.getMessage());\n        }\n        System.out.println(archive.fetch(\"ola/2026-11.pdf\").length + \" bytes\");\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"invoices.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype User struct {\n\tName         string\n\tIsAccountant bool\n}\n\ntype InvoiceArchive interface {\n\tFetch(path string) ([]byte, error)\n}\n\n// CloudInvoiceArchive is the real subject: expensive to create and to call.\ntype CloudInvoiceArchive struct{}\n\nfunc NewCloudInvoiceArchive() InvoiceArchive {\n\tfmt.Println(\"connecting to cloud storage...\")\n\treturn CloudInvoiceArchive{}\n}\n\nfunc (CloudInvoiceArchive) Fetch(string) ([]byte, error) { return make([]byte, 1024), nil }\n\n// SecuredInvoiceArchive is the proxy: same interface, access check and lazy creation.\ntype SecuredInvoiceArchive struct {\n\tuser User\n\treal func() InvoiceArchive\n}\n\nfunc NewSecuredInvoiceArchive(create func() InvoiceArchive, user User) *SecuredInvoiceArchive {\n\treturn &SecuredInvoiceArchive{user: user, real: sync.OnceValue(create)}\n}\n\nfunc (p *SecuredInvoiceArchive) Fetch(path string) ([]byte, error) {\n\tif !p.user.IsAccountant && !strings.HasPrefix(path, p.user.Name+\"/\") {\n\t\treturn nil, fmt.Errorf(\"%s cannot read %s\", p.user.Name, path)\n\t}\n\treturn p.real().Fetch(path) // the real archive is created on the first allowed call\n}\n\nfunc main() {\n\tarchive := NewSecuredInvoiceArchive(NewCloudInvoiceArchive, User{Name: \"ola\"})\n\tif _, err := archive.Fetch(\"jan/2026-11.pdf\"); err != nil {\n\t\tfmt.Println(err) // denied before any connection is opened\n\t}\n\tpdf, _ := archive.Fetch(\"ola/2026-11.pdf\")\n\tfmt.Println(len(pdf), \"bytes\")\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"invoices.py"},"content":[{"type":"text","text":"from collections.abc import Callable\nfrom dataclasses import dataclass\nfrom functools import cached_property\nfrom typing import Protocol\n\n\n@dataclass(frozen=True)\nclass User:\n    name: str\n    is_accountant: bool = False\n\n\nclass InvoiceArchive(Protocol):\n    def fetch(self, path: str) -> bytes: ...\n\n\nclass CloudInvoiceArchive:\n    \"\"\"Real subject: expensive to create (opens a connection) and to call.\"\"\"\n\n    def __init__(self) -> None:\n        print(\"connecting to cloud storage...\")\n\n    def fetch(self, path: str) -> bytes:\n        return bytes(1024)  # pretend this is a PDF\n\n\nclass SecuredInvoiceArchive:\n    \"\"\"Proxy: same interface; checks access and creates the real archive only when needed.\"\"\"\n\n    def __init__(self, create_real: Callable[[], InvoiceArchive], user: User) -> None:\n        self._create_real = create_real\n        self._user = user\n\n    @cached_property\n    def _real(self) -> InvoiceArchive:  # virtual proxy: built on first access\n        return self._create_real()\n\n    def fetch(self, path: str) -> bytes:\n        if not self._user.is_accountant and not path.startswith(f\"{self._user.name}/\"):\n            raise PermissionError(f\"{self._user.name} cannot read {path}\")\n        return self._real.fetch(path)\n\n\nif __name__ == \"__main__\":\n    archive: InvoiceArchive = SecuredInvoiceArchive(CloudInvoiceArchive, User(\"ola\"))\n    try:\n        archive.fetch(\"jan/2026-11.pdf\")  # denied before any connection is opened\n    except PermissionError as e:\n        print(e)\n    print(len(archive.fetch(\"ola/2026-11.pdf\")), \"bytes\")"}]}]}]},"toc":[{"id":"problem-archiwum-faktur-dla-wszystkich-i-od-razu","text":"Problem: archiwum faktur dla wszystkich i od razu","level":2,"locked":false},{"id":"rozwiazanie-zastepca-o-tym-samym-interfejsie","text":"Rozwiązanie: zastępca o tym samym interfejsie","level":2,"locked":false},{"id":"rodzaje-pelnomocnikow","text":"Rodzaje pełnomocników","level":3,"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-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":"szybki-test","text":"Szybki test","level":2,"locked":true},{"id":"podsumowanie","text":"Podsumowanie","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":36,"visibleBlocks":16,"resources":[{"id":"6b0857c83c96f2d34d0b4a23","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=hTC3rmRBIxs","embedUrl":"https://www.youtube-nocookie.com/embed/hTC3rmRBIxs","title":"Proxy vs Adapter vs Facade Pattern | Code Walks 012","description":"What is really the difference between the proxy pattern, adapter pattern, and the facade pattern? ► 01:50 Common denominator ► 02:36 The quick explanation ► 03:20 Proxy pattern ► 04:59 Adapter pattern ► 07:10 Facade pattern ARTICLE MENTIONED ►…","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/hTC3rmRBIxs/hqdefault.jpg","durationSec":null,"lang":"en","topics":["adapter","facade","proxy"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2016-07-16T09:26:16.000Z","popularity":58,"verifiedAt":"2026-11-26T10:57:20.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857b13c96f2d34d0b3360","type":"article","provider":"devto","url":"https://dev.to/mayallo/facade-vs-proxy-vs-adapter-design-patterns-3mfa","embedUrl":null,"title":"Facade vs Proxy vs Adapter Design Patterns","description":"Facade vs Proxy vs Adapter Design Patterns Understand the core differences, use cases,...","author":"Mohamed Mayallo","thumbnailUrl":"https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fmayallo.com%2Fwp-content%2Fuploads%2F2025%2F05%2Fadapter-facade-proxy-design-patterns.avif","durationSec":null,"lang":"en","topics":["adapter","facade","proxy"],"techs":["typescript"],"tags":["design-patterns","software-architecture","designpatterns","architecture","typescript","node"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"devto","publishedAt":"2025-05-12T08:37:54.000Z","popularity":46,"verifiedAt":"2026-11-26T10:52:11.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857bf3c96f2d34d0b4243","type":"article","provider":"web","url":"https://refactoring.guru/design-patterns/proxy","embedUrl":null,"title":"Proxy","description":"Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"en","topics":["proxy"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":70,"verifiedAt":"2026-11-26T11:26:03.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857a43c96f2d34d0b320c","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=tv-_1er1mWI","embedUrl":"https://www.youtube-nocookie.com/embed/tv-_1er1mWI","title":"10 Design Patterns Explained in 10 Minutes","description":"","author":"Fireship","thumbnailUrl":"https://i.ytimg.com/vi/tv-_1er1mWI/hqdefault.jpg","durationSec":null,"lang":"en","topics":["singleton","prototype","builder","factory-method","facade","proxy","iterator","observer","mediator","state"],"techs":["typescript"],"tags":[],"price":"free","featured":true,"featuredOrder":5,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:36.249Z","updatedAt":"2026-11-26T16:00:36.249Z"},{"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":[{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Wzorce projektowe – podstawy","summary":"Sześć pytań o klasyczne wzorce GoF: grupy, przeznaczenie i różnice.","servedLang":"pl","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"},{"id":"6b093ddebd4755deb67ee080","slug":"lru-cache","title":"Pamięć podręczna LRU","summary":"Cache o stałej pojemności, który przy przepełnieniu wyrzuca najdawniej używany wpis. get i put w O(1) – mapa plus lista dwukierunkowa.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":["proxy"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["design","hash-map","linked-list","caching","data-structures"],"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:54.691Z"},{"id":"6b093dddbd4755deb67ee061","slug":"debounce-throttle","title":"Debounce i throttle","summary":"Dwie klasyczne funkcje wyższego rzędu z frontendu – debounce (wywołaj po ciszy) i throttle (najwyżej raz na okres) – z cancel, flush, zachowaniem this i wstrzykiwanymi timerami.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":["decorator"],"techs":["typescript","javascript"],"tags":["javascript","closures","timers","event-loop","higher-order-functions"],"languages":["typescript","javascript"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.681Z"},{"id":"6b093dc291bd8fbaf2a0c8e0","slug":"rate-caching-proxy","title":"Pełnomocnik z pamięcią kursów walut","summary":"Dwa pełnomocniki przed wolnym API banku – buforujący z czasem życia wpisu i leniwy, który tworzy połączenie dopiero przy pierwszym użyciu. Mają ten sam interfejs, więc da się je składać.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["proxy"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["proxy","caching","lazy-loading","ttl","structural"],"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.583Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-structural","title":"Wzorce strukturalne GoF","items":[{"slug":"adapter","title":"Adapter – jak dogadać się z kodem, który mówi innym językiem","current":false},{"slug":"bridge","title":"Most (Bridge) – dwie osie zmian bez eksplozji klas","current":false},{"slug":"composite","title":"Kompozyt (Composite) – drzewa, w których liść i gałąź wyglądają tak samo","current":false},{"slug":"decorator","title":"Dekorator (Decorator) – dokładanie zachowania warstwa po warstwie","current":false},{"slug":"facade","title":"Fasada (Facade) – jedno proste wejście do skomplikowanego podsystemu","current":false},{"slug":"flyweight","title":"Pyłek (Flyweight) – jak zmieścić w pamięci 60 tysięcy miejsc na stadionie","current":false},{"slug":"proxy","title":"Pełnomocnik (Proxy) – zastępca, który kontroluje dostęp do prawdziwego obiektu","current":true}]}],"prev":{"slug":"flyweight","title":"Pyłek (Flyweight) – jak zmieścić w pamięci 60 tysięcy miejsc na stadionie"},"next":null,"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}]}}