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

I have a set of classes that work together (I code in javascript).

There is one parent class and several child classes that are created by the parent class. I have several clients of these classes, each of which must add one or more methods to the parent or child classes.

Instead of every client inheriting from these classes, which is doable, but randomly due to child classes, I have these clients passing functions to the parent class when they instantiate the main class.

The main class dynamically creates methods, and clients can call methods similar to the ones they were there all the time.

My questions:

  • Is this a reasonable thing?
  • What will be the design pattern for what I'm doing?
+3
source share
4 answers

The strategy template is designed for situations when you get your strategy at runtime. may be applicable here. The strategy in this case is a class that corresponds to the behavior, that is, it has a "execute" method or something else.

A decorator pattern may also be used . It is also a runtime template, but it extends the class that it adorns at the method level.

So, a strategy template is good if you select a class dynamically, and Decorator is good if you only change the method implementation at runtime.

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

+3

, "", , javascript. , "" "" ( javascript ).

javascript , :

foo.prototype.bar = function() {};

, bar foo, bar - foo. , .

( / )

+2

, , .

: , , . "" "-" JavaScript.

// JavaScript, , , // .

JavaScript . , , , , .

0

hvgotcodes, , , ( .)

Instead, you should provide a member that takes the function as a value.

eg.

function MyClass() {
    this.myFunction = defaultFunction;

    this.defaultFunction = function() {
       // do something by default.
       alert("using default");
    }

    this.doFunction = function() {
       // something that calls myFunction.
       this.myFunction();
    }
}

---8< snip --------

// later on...

t = new MyClass();
t.doFunction(); // output 'using default'
t.myFunction = function(){ 
   // do something specific with this instance, when myFunction is called. 
   alert("customized for this instance.");
}
t.doFunction(); // output 'customized for this instance.'
0
source

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


All Articles