Proxy Pattern Override

Suppose there is a Subject interface.

interface Subject { void request(); }

We have a RealSubject class. Suppose we want to improve RealSubject, we can either use a proxy template that wraps around RealSubject:

class Proxy implements Subject { 
   private RealSubject ref;
   void request(){ ... }
}

or we can extend RealSubject and override the method

class EnhancedSubject extends RealSubject {
   @Override
   void request() { ... }
}

Which approach is better? I know the Liskov principle; Assume that EnhancedSubject satisfies the Liskov principle. Do you still consider the legacy?

If there is no interface object (i.e., RealSubject does not implement any interface), it seems that "inheritance and redefinition" is the only option, since there is no interface for implementation in the proxy template. Can you apply a proxy template if there is no Subject interface?

+3
2

, " "?

Interface Proxy ( Decorator), - . (.: 16: Java (2- ))

(RealSubject) , , (EnhancedSubject). , : .

: " EnhancedSubject , ?"

, RealSubject EnhancedSubject , .

, , , , - Unit .

. , Unit Unit, mock- RealSubject Proxy Subject, Proxy, , RealSubject EnhancedSubject, , EnhancedSubject .

, , API, , Concrete- . Keep It Simple Stupid (K.I.S.S.) - .

" , Subject?" RealSubject RealSubject , API, RealSubject, , , Inheritance.

+6

/ , . . ( , java.. )

, , - :

class LoggingSubjectProxy implements Subject
{
   private Subject ref;
   void request() 
   { 
      log("Called request");
      ref.request();
   }
}

LoggingSubjectProxy l;
if(dosimple)
{
    l.ref = SimpleSubject();
}
else
{
    l.ref = ComplexSubject();
}
l.request()

, .

+1

Source: https://habr.com/ru/post/1770237/


All Articles