i am looking to simulate interface and DTO in javascript for this problem.
an object dto, an object caller and different implementation for the same Interface IWorker.
caller will recieve a dto for instantiation, will feed it with user inputs, and then call the correct implementation of Iworker (method execute).
I want that in my code i have juste one instance of dto, and one instance of caller, so i will have juste to call caller.CallWorker() everytime the user make another choice
Please tell me if the idea is good or not and any implementation in javascript is welcome
Thanks a lot
Edit :
Thanks for help, will take Bergi solution, but i need one more thing
So my implementation will be like this :
var caller = {
callWorker: function(obj) {
if(obj.id == 1) Worker1.execute();
if(obj.id == 2) Worker2.execute();
if(obj.id == 2) Worker3.execute();
}
};
but this means that i have to add all worker defintions(one js script per implementation) in the html page.
I want to just add dynamically the scripts, in fact active worker depends on a lot of business logic, so i will include them dynamically to have only active workers in the page.
How do you recommend me to do ? Do all conditions in caller.callworker ? or there is more elegant approach.
There are no “interfaces” in the dynamical typed language JavaScript, as well as there are no classes. The nearest simulation is a function that checks whether a given object has a certain set of methods; yet it cannot make any type or functionality tests.
The nearest thing to a DTO is a JSON-serialisable object. That means it has no cycles, does not contain
Dateobjects or even host objects.That’s another design pattern: Singletons. They can be easily coded in JS, since objects can be created on the fly and don’t need a class and a constructor that needs to prevent multiple instantiation. Just use object literals for them.
It’s just a simple example, but you can extend it where you need:
Make workers an array or object. For example