Why does the proxy pattern require inheritance?

877 views Asked by At

Looking at the UML diagram on wikipedia, both the proxy class and the subject class(es) implement the same interface.

From what I understand, the purpose of the proxy class is delegation. This can be done via composition; the delegated class(es) do not have to implement the same interface.

Is there a reason the subject class(es) have to implement the same interface as the proxy class?

3

There are 3 answers

3
dkatzel On BEST ANSWER

Is there a reason the subject class(es) have to implement the same interface as the proxy class?

Yes but it's the other way around the proxy has to implement the same interface as the subject

The Client doesn't realize that the instance it is using is a proxy! The Client thinks it's a Subject

0
Vladimir On

Proxy and Subject should provide the same set of operations. Client cannot recognize what instance is requested, proxy or Subject. It is hidden for it. Because of it, both classes implement the same interface.

1
Karl On

That would be more like an Adapter (and object-Adapter, to use the terminology of the Gang of Four book). The Adapter is usually used when you discover later in a project that you need interface adaptation. You design proxies up-front, I believe.

One reason may be that Proxies should be transparent to your client. If Proxies have different interfaces than the Subjects then this transparency will be broken. Just think of a use case when not all of your Subject needs to be proxied, e.g. not all your objects are 'remote'.