I have a class that provides basic functionality of a modal window. For different situations I need to provide different modals(different number of buttons, titles, etc...). I have a kind of factory that can compose those modal windows, like in the example below.

class ModalProvider {
   static ModalWindow makeModalWindowOne(callback)  {
       AcceptButton acceptButton = new AcceptButton();
       ModalWindow mw = new ModalWindow();
       mw.addButton(acceptButton);
       acceptButton.onClick() {
          callback();
       }
       return mw;
   }
   static ModalWindow makeModalWindow2(callback) {
   // similar to previous but with different number of buttons   
   }

}

This approach works however it doesn't feel right. Especially the fact that I need to bind callback to button in a static function.

Is it an acceptable approach to compose object in this fashion in static functions?

To elaborate on this a little, the alternative solution I'm thinking of is creating subclasses of ModalWindow for each static function. So, I would have something like AcceptModalWindow, CreateModalWindow, etc...

有帮助吗?

解决方案

Yes, it's fine. Your other solution is probably also fine.

I expect that's basically just a re-arrangement of the code in your example

class ModalWindowOne : ModalWindow {
    private AcceptButton acceptButton;
    public ModalWindowOne(callback) {
        acceptButton = new AcceptButton();
        addButton(acceptButton);
        acceptButton.onClick = callback;
    }
}

class ModalWindowTwo : ModalWindow {
    private AcceptButton acceptButton;
    private RejectButton rejectButton;
    public ModalWindowTwo(callback) {
        ...
    }
}

Your worry "Especially the fact that I need to bind callback to button in a static function." seems weird. Why does it matter that you are doing an assignment in one kind of function rather than another? A constructor is exactly as statically accessible as a static function.

Compare

 ModalProvider.makeModalOne(foo);

 new ModalWindowOne(foo);

其他提示

If the ModalProvider requires no state, then there is nothing wrong with keeping it as static methods. The downside here is the same as using static functions anywhere: they are difficult to mock during unit testing.

Since this code seems deeply entrenched in the user interface, isolating this code from the UI in order to test it is unlikely.

Until your "ModalProvider" needs to maintain state, or you need to mock the creation of these modal windows for testing purposes, keeping them as static functions is fine.

许可以下: CC-BY-SA归因
scroll top