Proxy Pattern: controllare l'accesso senza cambiare l'interfaccia
Il problema: oggetti pesanti che non servono subito Hai un modello Article con una relazione comments() . La pagina del blog elenca 20 articoli con titolo, data e autore. Nessuno ha ancora cliccato su un articolo per vederne i commenti, eppure il codice carica tutte le relazioni in anticipo, eseguendo 21 query (una per gli articoli e una per i commenti di ciascuno). E il classico N+1 problem , ma…
The problem: heavy objects that are not needed immediately - An Article model with a comments() relationship. The blog page lists 20 articles with title, date, and author. No one has clicked an article yet for comments, yet the code loads all relationships in advance, executing 21 queries (one for the articles and one for comments of each).
The classic N+1 problem, but the root is deeper: the problem is that the Article object directly exposes comments, and the user has no way to decide when to load them. The Proxy Pattern solves this problem by inserting a surrogate (the proxy) between the client and the real object. The proxy implements the same interface as the real object, but controls when and how the real object is created or accessed. The client doesn't know it's talking to a proxy - for them, it's the same object.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written; read the original for the full account.


