Is there a design pattern for injecting methods into a class? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Is there a design pattern for injecting methods into a class? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a set of classes that work together (I’m coding in javascript).

There is one parent class and a number of child classes that are instantiated by the parent class. I have a number of clients of these classes that each need to add one or more methods to the parent or child classes.

Rather than having each client inherit from these classes, which is doable but messy because of the child classes, I am having these clients pass functions into the parent class when they instantiate the main class.

The main class creates the methods dynamically and the clients can call the methods like they were there all along.

My questions are:

  1. is this a sensible thing to do?
  2. what would the design pattern be for what I am doing?


The strategy pattern is for situations where you get your ‘strategy’ at runtime. might be applicable here. Strategy in this case is a class that conforms to a behavior, i.e. has a method like ‘execute’ or whatever.

The decorator pattern also might apply. It is also a runtime pattern, but augments the class it is decorating at the method level.

So the Strategy pattern is good if you are choosing a class dynamically, and Decorator is good if you are only changing out the method implementation at runtime.

(I took the decorator part of this answer with permission from ircmaxell)

We are here to answer your question about Is there a design pattern for injecting methods into a class? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji