I have an interface MyInterface
and a concrete implementation MyImplementation
that implements the interface. Now I need to create multiple "Wrappers" that should also implement MyInterface
and will be wrapping the original MyImplementation
object. Wrapping in a sense that properties and function methods on the wrapper will serve as a kind of Proxy
- i.e. performing some checks on the input data and pass it down to the original implementation of MyImplementation
. I need to stack the multiple wrappers into each others, i.e. have an MyValidator1
, MyValidator2
etc. that can be - depending on the use case - all added to a single object.
Some code to make things clearer:
interface MyInterface {
method1(arg1, arg2): any;
}
class MyImplementation implements MyInterface {
method1(arg1, arg2) {
/* perform checks and or throw */
}
}
class MyValidator1 implements MyInterface {
method1(arg1, arg2) {
/* ... */
}
}
class MyValidator2 implements MyInterface {
method1(arg1, arg2) {
/* ... */
}
}
let o1 = new MyImplementation();
// only apply validator1
AddValidator1(o1);
let o2 = new MyImplementation();
// only apply validator2
AddValidator2(o2);
let o3 = new MyImplementation();
// apply both validators
AddValidator1(o3);
AddValidator2(o3);
// intended call hierarchicy when calling o3.method1(arg1, arg2)
// MyValidator1.method1(arg1, arg2)
// MyValidator2.method1(arg1, arg2)
// MyImplemenation.method1(arg1, arg2)
// but the order of the validators is not important!
This is just some code suggestion, I am looking for all kinds of patterns that might differ from the above code to achieve this.
It is important that all instances of MyInterface
implemenations are encapsulated - they should behave as if they were MyImplemenation
to a consumer. The Validators should possibly add private functions or properties.
Whats the best way to do this? Maybe changing the prototype at runtime?