Прокси -паттерн
В компьютерном программировании прокси -шаблон представляет собой шаблон проектирования программного обеспечения . Прокси . , в его наиболее общей форме, является классом, функционирующим как интерфейс для чего -то другого Прокси может взаимодействовать с чем угодно: сетевое соединение, большой объект в памяти, файл или какой -либо другой ресурс, который дорого или невозможно продублировать. Короче говоря, прокси - это обертка или объект агента, который называется клиентом, чтобы получить доступ к реальному объекту служения за кулисами. Использование прокси может просто пересылать в реальном объекте или может обеспечить дополнительную логику. В доверенности можно предоставить дополнительные функциональность, например, кэширование, когда операции на реальном объекте являются ресурсными интенсивными или проверяют предварительные условия до того, как будут вызоваться операции на реальном объекте. Для клиента использование прокси -объекта аналогично использованию реального объекта, поскольку оба реализуют один и тот же интерфейс.
Обзор
[ редактировать ]Прокси [ 1 ] Паттерн дизайна является одним из двадцать три известных GOF Design Patterns Это описывает, как решить повторяющиеся задачи проектирования для проектирования гибкого и многократного объектно-ориентированного программного обеспечения, то есть объектов, которые легче реализовать, изменять, тестировать и повторно использовать.
Какие проблемы может решить шаблон дизайна прокси? [ 2 ]
[ редактировать ]- Доступ к объекту должен контролироваться.
- Additional functionality should be provided when accessing an object.
When accessing sensitive objects, for example, it should be possible to check that clients have the needed access rights.
What solution does the Proxy design pattern describe?
[edit]Define a separate Proxy
object that
- can be used as substitute for another object (
Subject
) and - implements additional functionality to control the access to this subject.
This makes it possible to work through a Proxy
object to perform additional functionality when accessing a subject. For example, to check the access rights of clients accessing a sensitive object.
To act as substitute for a subject, a proxy must implement the Subject
interface.
Clients can't tell whether they work with a subject or its proxy.
See also the UML class and sequence diagram below.
Structure
[edit]UML class and sequence diagram
[edit]
In the above UML class diagram,
the Proxy
class implements the Subject
interface so that it can act as substitute for Subject
objects. It maintains a reference (realSubject
)
to the substituted object (RealSubject
) so that it can forward requests to it
(realSubject.operation()
).
The sequence diagram
shows the run-time interactions: The Client
object
works through a Proxy
object that
controls the access to a RealSubject
object.
In this example, the Proxy
forwards the request to the RealSubject
, which performs the request.
Class diagram
[edit]

Possible usage scenarios
[edit]Remote proxy
[edit]In distributed object communication, a local object represents a remote object (one that belongs to a different address space). The local object is a proxy for the remote object, and method invocation on the local object results in remote method invocation on the remote object. An example would be an ATM implementation, where the ATM might hold proxy objects for bank information that exists in the remote server.
Virtual proxy
[edit]In place of a complex or heavy object, a skeleton representation may be advantageous in some cases. When an underlying image is huge in size, it may be represented using a virtual proxy object, loading the real object on demand.
Protection proxy
[edit]A protection proxy might be used to control access to a resource based on access rights.
See also
[edit]References
[edit]- ^ Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 207ff. ISBN 0-201-63361-2.
{{cite book}}
: CS1 maint: multiple names: authors list (link) - ^ "The Proxy design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-12.
- ^ "The Proxy design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.
External links
[edit]

- Geary, David (February 22, 2002). "Take control with the Proxy design pattern". JavaWorld. Retrieved 2020-07-20.
- PerfectJPattern Open Source Project, Provides componentized implementation of the Proxy Pattern in Java
- Adapter vs. Proxy vs. Facade Pattern Comparison at the Wayback Machine (archived 2012-03-11)
- Proxy Design Pattern
- Proxy pattern C++ implementation example at the Wayback Machine (archived 2014-10-19)
- Proxy pattern description from the Portland Pattern Repository