Overriding an internal method with Decorator Design Pattern

I am writing an object-oriented code in which I am trying to use Decorator pattern to implement a variety of optimizations to be applied on a family of core classes at runtime. The main behaviour of core classes is a complex behaviour that is fully implemented in those classes, which indeed calls other internal methods to fulfill pieces of the task. The decorators will only customize the internal methods which are called by the complex behaviour in core class.

Here is a pseudo-code of what I’m trying to reach:

interface I{   complex();   step1();   step2(); } 
class C implements I{   complex(){     ...     this.step1();     ...     this.step2();   }   step1(){     ...   }   step2(){     ...   } } 
abstract class Decorator implements I{   I wrapped;   constructor(I obj){     this.wrapped = obj;   }   complex(){     this.wrapped.complex();   }   step1(){     this.wrapped.step1();   }   step2(){     this.wrapped.step2();   } } 
class ConcreteDecorator extends Decorator{   constructor(I obj){     super(obj);   }   step2(){     ... // customizing step2()   } } 

There are a variety of customizations possible which could be combined together, and that is the main reason I’m using decorator pattern. otherwise I’ll get to create dozens to hundred subtypes for each possible combination of customizations.

Now if I try to create object of the decorated class:

x = new C(); y = new ConcreteDecorator(x); y.complex(); 

I expect the complex() method to be executed form the wrapped core object, while using the overridden step2() method from decorator. But it does not work this way as the complex() method in abstract decorator directly calls the method on core object which indeed skips the overridden step2() in decorator.

My overall goal is to enable the decorators only overriding one or few of the stepx() methods and that would be invoked by the complex() method which is already implemented in the core object and invokes all the steps.

Could this functionality be implemented using Decorator design pattern at all? If yes how, and if not what is the appropriate design pattern for tackling this problem.

Thanks.

Service decorator for entity list builder?

Is it possible to use a service decorator, or similar mechanism, to override a method in an entity’s list builder?

For my specific use case, I want to override the render() method of the Drupal\webform\WebformSubmisionListBuilder class, which is the list builder for the Drupal\webform\Entity\WebformSubmission entity. I’d prefer to not have to replace the list builder class entirely.

I did come across this post, but it doesn’t seem to provide a solution to my use case. I also didn’t fully comprehend the information in the post, so I might have missed the solution.

Lazy evaluation function decorator

Suppose I have some expensive function expensive_computation which takes a long time to compute but it always returns the same value.

I want to avoid paying the cost of computing this function because it may never be called.

Here is my solution to this, is there a more obvious or clean way to do it? Or maybe even some function from the standard library?

def lazy(function):    internal_state = None    def lazy_evaluation():     nonlocal internal_state     if internal_state is None:       internal_state = function()     return internal_state    return lazy_evaluation  @lazy def expensive_computation():   print("Working ...")   return "that was hard"  print(expensive_computation()) print(expensive_computation()) 

Which prints:

Working ... that was hard that was hard 

A simple decorator written as a class, which counts how many times a function has been called

Can I improve its typing? Is there any other improvement or pythonic change that you would do?

F = TypeVar('F', bound=Callable[..., Any])   # This is mostly so that I practice using a class as a decorator. class CountCalls:     """Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`."""     def __init__(self, func: F) -> None:         functools.update_wrapper(self, func)         self.func = func         self.num_calls: int = 0         self._logger = logging.getLogger(__name__ + '.' + self.func.__name__)         self.last_return_value = None      def __call__(self, *args: Any, **kwargs: Any) -> Any:         self.num_calls += 1         self._logger.debug(' called %s times', self.num_calls)         self.last_return_value = self.func(*args, **kwargs)         return self.last_return_value 

Here’s the decorator in action:

@CountCalls def asdf(var: str):     print(var)     return len(var) asdf(5) Traceback (most recent call last):   File "<input>", line 1, in <module>   File "C:/Projects/Python/he/src/he/decorators.py", line 139, in __call__     self.last_return_value = self.func(*args, **kwargs)   File "<input>", line 4, in asdf TypeError: object of type 'int' has no len() 5 asdf('Laur') Laur 4 asdf.last_return_value 4 asdf('fake gangsta') fake gangsta 12 

Django custom cache_page decorator

I am trying to override my django app’s(restful API to be precise) caching. So it seems SessionMiddleware is setting vary header to Cookie.

Because of this, every user has its own cache. But for my use case it does not need to have unique cache for every user. If a first person visited that route i want to cache it and serve cache to everyone(each user) since it’s just a read-only endpoint.

Because of vary: Cookie, it’s not possible for default django cache. Cookie is different for any user. I dug django cache codes and found CacheMiddleWare is using UpdateCacheMiddleware, FetchFromCacheMiddleware Based on this i just had to write my own cache_page decorator just for certain Viewsets instead of writing whole middleware.

All Middlewares(UpdateCacheMiddleware, FetchFromCacheMiddleWare) are extended from MiddlewareMixin Checking vary header is in UpdateCacheMiddleWare i tried overriding UpdateCacheMiddleWare but no luck. Please if anyone have solution please tell me. Thanks in advance.

decorator pattern for generating complete html

I am trying to figure out the best way to decorate html. What I mean is replacing specific syntax string with the actual content.

Kind of like, razor syntax in Asp.net MVC using <%= %>.

Currently, I have an HTML page with design and I just need to replace tags (for ex: <%HISTORICTABLE%>) with actual content.

I have 5-6 tags in HTML that needs to be replaced with the original html.

I might add new/remove tags (‘behaviour’) from html.

I think decorator pattern should do the trick or would you think its an overkill?

On using decorator and strategy pattern for dynamically generating SQL queries in JAVA

This part of the application design deals with generating sql query strings dynamically

This is a link to my application that actually has the design specified in the image.

The Idea behind the image is that the SubjectInfoViewer behaves as the context in the strategy pattern, and the ViewingQueryComponent behaves as the strategy interface, as well as the component class in the decorator pattern, and its implementing classes except the Filter class are the different strategies. These strategies return an sql string specific to their description, which can be decorated using the Filter class, which is the decorator, in the decorator pattern. The classes implementing the filter class just append the where clause of the sql string produced by the strategies and push the parameters involved in the where clause in a parameter stack, so they can finally by used by a parameterized sql statement involving the whole “stitched” sql string.

For some reason, this doesn’t seem to be the right approach to tackle this particular usecase. Kindly suggest the best practices used in this situation.