2

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?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
neverendingqs
  • 4,006
  • 3
  • 29
  • 57

3 Answers3

4

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

dkatzel
  • 31,188
  • 3
  • 63
  • 67
  • 1
    Is this only valuable if a factory is involved? If the client is using the subject, and later I want it to use the proxy instead, how can I do so? (also vice versa). – neverendingqs Dec 14 '14 at 21:34
  • 1
    You are correct that in order to keep the `Client` ignorant of which implementation it is, you have to provide the `Subject` instance (either proxy or the real subject) to the Client. This can be done via the factory pattern but can also be dependency injected via a constructor or method call. – dkatzel Dec 15 '14 at 05:46
  • If the client is using the subject before that pattern, you will have to modify the Client so that it uses the Proxy pattern's Subject abstraction (which looks almost like the old subject). Then the Client does't know if it's talking to a Subject or its Proxy. – Fuhrmanator Dec 15 '14 at 14:18
1

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.

Vladimir
  • 2,066
  • 15
  • 13
1

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'.

Karl
  • 3,170
  • 1
  • 21
  • 28
  • I think this question helped me understand the differences: http://stackoverflow.com/questions/350404/how-do-the-proxy-decorator-adapter-and-bridge-patterns-differ – neverendingqs Dec 15 '14 at 18:00