Artykuł · Pełnomocnik · Dekorator
Pełnomocnik (Proxy) – zastępca, który kontroluje dostęp do prawdziwego obiektu
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.
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. Pełnomocnik (ang. Proxy) 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ć.
Problem: archiwum faktur dla wszystkich i od razu
Platforma kursów przechowuje faktury w PDF w chmurowym magazynie plików. Klasa CloudInvoiceArchive przy tworzeniu otwiera połączenie i uwierzytelnia się, co trwa kilkaset milisekund. Kod wyglądał tak:
const archive = new CloudInvoiceArchive(); // connects on every request, even if unused
app.get("/invoices/:path(*)", async (req, res) => {
// every developer has to remember this check – and one endpoint forgot it
if (!req.user.isAccountant && !req.params.path.startsWith(`${req.user.name}/`)) {
return res.status(403).end();
}
res.send(await archive.fetch(req.params.path));
});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.
Rozwiązanie: zastępca o tym samym interfejsie
Tworzymy SecuredInvoiceArchive, który implementuje ten sam interfejs InvoiceArchive. Pełnomocnik zna bieżącego użytkownika i funkcję tworzącą prawdziwe archiwum. Przy każdym fetch() najpierw sprawdza uprawnienia, a prawdziwe archiwum tworzy dopiero przy pierwszym dozwolonym wywołaniu. Kontrolery dostają pełnomocnika i nie muszą pamiętać o niczym.
| Rola | W przykładzie | Odpowiedzialność |
|---|---|---|
| Podmiot (Subject) | InvoiceArchive | wspólny interfejs oryginału i pełnomocnika |
| Prawdziwy podmiot (Real Subject) | CloudInvoiceArchive | właściwa praca – pobranie pliku z magazynu |
| Pełnomocnik (Proxy) | SecuredInvoiceArchive | kontrola dostępu i leniwe utworzenie oryginału |
| Klient | kontroler faktur | korzysta z interfejsu, nie wie o pełnomocniku |
Rodzaje pełnomocników
| Rodzaj | Co robi | Przykład z życia |
|---|---|---|
| Wirtualny (virtual) | tworzy kosztowny obiekt dopiero przy pierwszym użyciu | leniwe ładowanie encji w ORM |
| Ochronny (protection) | sprawdza uprawnienia przed delegacją | nasze archiwum faktur |
| Zdalny (remote) | ukrywa komunikację sieciową za lokalnym interfejsem | klient wygenerowany z gRPC lub OpenAPI |
| Buforujący (caching) | zwraca zapamiętany wynik zamiast pytać oryginał | cache odpowiedzi drogiego API |
| Rejestrujący (smart reference) | liczy referencje, loguje, mierzy | liczniki wywołań, audyt dostępu |
Implementacja w pięciu językach
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 Lazy<T> w C#, metodzie synchronized w Javie i sync.OnceValue w Go; w Pythonie posłużył functools.cached_property.
SecuredInvoiceArchive
var ola = new User("ola", IsAccountant: false);
IInvoiceArchive archive = new SecuredInvoiceArchive(() => new CloudInvoiceArchive(), ola);
try { archive.Fetch("jan/2026-11.pdf"); } // denied before any connection is opened
catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); }
Console.WriteLine($"{archive.Fetch("ola/2026-11.pdf").Length} bytes"); // connects now
public sealed record User(string Name, bool IsAccountant);
public interface IInvoiceArchive
{
byte[] Fetch(string path);
}
// Real subject: expensive to create (opens a connection) and to call.
public sealed class CloudInvoiceArchive : IInvoiceArchive
{
public CloudInvoiceArchive() => Console.WriteLine("connecting to cloud storage...");
public byte[] Fetch(string path) => new byte[1024]; // pretend this is a PDF
}
// Proxy: same interface; checks access and creates the real archive only when needed.
public sealed class SecuredInvoiceArchive(Func<IInvoiceArchive> createReal, User user) : IInvoiceArchive
{
private readonly Lazy<IInvoiceArchive> _real = new(createReal); // thread-safe lazy creation
public byte[] Fetch(string path)
{
if (!user.IsAccountant && !path.StartsWith($"{user.Name}/", StringComparison.Ordinal))
throw new UnauthorizedAccessException($"{user.Name} cannot read {path}");
return _real.Value.Fetch(path);
}
}interface User {
name: string;
isAccountant: boolean;
}
interface InvoiceArchive {
fetch(path: string): Promise<Uint8Array>;
}
// Real subject: expensive to create (opens a connection) and to call.
class CloudInvoiceArchive implements InvoiceArchive {
constructor() {
console.log("connecting to cloud storage...");
}
async fetch(path: string): Promise<Uint8Array> {
return new Uint8Array(1024); // pretend this is a PDF
}
}
// Proxy: same interface; checks access and creates the real archive only when needed.
class SecuredInvoiceArchive implements InvoiceArchive {
private real?: InvoiceArchive;
constructor(private readonly createReal: () => InvoiceArchive, private readonly user: User) {}
async fetch(path: string): Promise<Uint8Array> {
if (!this.user.isAccountant && !path.startsWith(`${this.user.name}/`)) {
throw new Error(`${this.user.name} cannot read ${path}`);
}
this.real ??= this.createReal(); // virtual proxy: connect on first allowed call
return this.real.fetch(path);
}
}
const archive: InvoiceArchive = new SecuredInvoiceArchive(() => new CloudInvoiceArchive(), {
name: "ola",
isAccountant: false,
});
archive
.fetch("jan/2026-11.pdf")
.catch((e: Error) => console.log(e.message)) // denied before any connection is opened
.then(() => archive.fetch("ola/2026-11.pdf"))
.then((pdf) => console.log(`${pdf.length} bytes`));import java.util.function.Supplier;
record User(String name, boolean isAccountant) {}
interface InvoiceArchive {
byte[] fetch(String path);
}
// Real subject: expensive to create (opens a connection) and to call.
class CloudInvoiceArchive implements InvoiceArchive {
CloudInvoiceArchive() { System.out.println("connecting to cloud storage..."); }
public byte[] fetch(String path) { return new byte[1024]; } // pretend this is a PDF
}
// Proxy: same interface; checks access and creates the real archive only when needed.
final class SecuredInvoiceArchive implements InvoiceArchive {
private final Supplier<InvoiceArchive> createReal;
private final User user;
private InvoiceArchive real;
SecuredInvoiceArchive(Supplier<InvoiceArchive> createReal, User user) {
this.createReal = createReal;
this.user = user;
}
public byte[] fetch(String path) {
if (!user.isAccountant() && !path.startsWith(user.name() + "/"))
throw new SecurityException(user.name() + " cannot read " + path);
return realArchive().fetch(path);
}
private synchronized InvoiceArchive realArchive() {
if (real == null) real = createReal.get(); // virtual proxy: connect on first allowed call
return real;
}
}
public class Invoices {
public static void main(String[] args) {
InvoiceArchive archive = new SecuredInvoiceArchive(CloudInvoiceArchive::new, new User("ola", false));
try {
archive.fetch("jan/2026-11.pdf"); // denied before any connection is opened
} catch (SecurityException e) {
System.out.println(e.getMessage());
}
System.out.println(archive.fetch("ola/2026-11.pdf").length + " bytes");
}
}package main
import (
"fmt"
"strings"
"sync"
)
type User struct {
Name string
IsAccountant bool
}
type InvoiceArchive interface {
Fetch(path string) ([]byte, error)
}
// CloudInvoiceArchive is the real subject: expensive to create and to call.
type CloudInvoiceArchive struct{}
func NewCloudInvoiceArchive() InvoiceArchive {
fmt.Println("connecting to cloud storage...")
return CloudInvoiceArchive{}
}
func (CloudInvoiceArchive) Fetch(string) ([]byte, error) { return make([]byte, 1024), nil }
// SecuredInvoiceArchive is the proxy: same interface, access check and lazy creation.
type SecuredInvoiceArchive struct {
user User
real func() InvoiceArchive
}
func NewSecuredInvoiceArchive(create func() InvoiceArchive, user User) *SecuredInvoiceArchive {
return &SecuredInvoiceArchive{user: user, real: sync.OnceValue(create)}
}
func (p *SecuredInvoiceArchive) Fetch(path string) ([]byte, error) {
if !p.user.IsAccountant && !strings.HasPrefix(path, p.user.Name+"/") {
return nil, fmt.Errorf("%s cannot read %s", p.user.Name, path)
}
return p.real().Fetch(path) // the real archive is created on the first allowed call
}
func main() {
archive := NewSecuredInvoiceArchive(NewCloudInvoiceArchive, User{Name: "ola"})
if _, err := archive.Fetch("jan/2026-11.pdf"); err != nil {
fmt.Println(err) // denied before any connection is opened
}
pdf, _ := archive.Fetch("ola/2026-11.pdf")
fmt.Println(len(pdf), "bytes")
}from collections.abc import Callable
from dataclasses import dataclass
from functools import cached_property
from typing import Protocol
@dataclass(frozen=True)
class User:
name: str
is_accountant: bool = False
class InvoiceArchive(Protocol):
def fetch(self, path: str) -> bytes: ...
class CloudInvoiceArchive:
"""Real subject: expensive to create (opens a connection) and to call."""
def __init__(self) -> None:
print("connecting to cloud storage...")
def fetch(self, path: str) -> bytes:
return bytes(1024) # pretend this is a PDF
class SecuredInvoiceArchive:
"""Proxy: same interface; checks access and creates the real archive only when needed."""
def __init__(self, create_real: Callable[[], InvoiceArchive], user: User) -> None:
self._create_real = create_real
self._user = user
@cached_property
def _real(self) -> InvoiceArchive: # virtual proxy: built on first access
return self._create_real()
def fetch(self, path: str) -> bytes:
if not self._user.is_accountant and not path.startswith(f"{self._user.name}/"):
raise PermissionError(f"{self._user.name} cannot read {path}")
return self._real.fetch(path)
if __name__ == "__main__":
archive: InvoiceArchive = SecuredInvoiceArchive(CloudInvoiceArchive, User("ola"))
try:
archive.fetch("jan/2026-11.pdf") # denied before any connection is opened
except PermissionError as e:
print(e)
print(len(archive.fetch("ola/2026-11.pdf")), "bytes")Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok po kroku
- Kiedy stosować, a kiedy nie
- Powiązania z innymi wzorcami
- W praktyce
- Szybki test
- Podsumowanie