Why would I use the proxy instead of direct call to RealSubject?

I’m actually reading about the Proxy design pattern (https://refactoring.guru/design-patterns/proxy) and I’m wondering about what does prevent the Client to call directly the RealSubject class.

I give you this illustration that i’ve found on this post :

enter image description here

I can’t understand how to prevent client for making the mistake of calling the RealSubject directly instead of the Proxy object.

What I would like to do is to obligate the client to call the Proxy object, so the Proxy object can filtering access and logging access ect…

I’ve even buy this book and read the part about Proxy, and have also looked at the code example which is given :

Proxy design pattern code
echo "Client: Executing the client code with a real subject:n";
$realSubject = new RealSubject();

echo "n";

echo "Client: Executing the same client code with a proxy:n";
$proxy = new Proxy($realSubject);

So here in this code snippet it seams to be allowed to call directly the realSubject without using the Proxy.

So maybe I’m not looking at the good design pattern, maybe there exist one which would suit my requirement of forcing client to call the ‘Proxy’, and not allow to call the RealSubject ?

I’m wondering about what does prevent the Client to call directly the RealSubject class.

In general, nothing prevents this. That doesn’t mean you don’t have mechanisms you can use to prevent this, but in general they won’t be a “design pattern” per se; design patterns are not the be all and end all of good software engineering.

Some ways you can prevent (or at least reduce) calling RealSubject directly:

  1. Code reviews. If you see anything other than the proxy calling RealSubject, you reject the code.
  2. Scope RealSubject so it is not visible to the client code (may or may not be possible in your language).
  3. When creating your DI container, make sure the proxy is registered and RealSubject is not – this makes it much harder for anyone to accidentally call RealSubject.
  4. Static code analysis in your CI system which errors on any direct calls to RealSubject.

Many more exist, which ones are appropriate for your environment is something you’ll have to work out. Personally, I’ve never found a need for anything other teaching/reminding developers and code reviews.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *