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?

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

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

Comments

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

1 Comment

I think this question helped me understand the differences: stackoverflow.com/questions/350404/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.