design-patternsfactory-method

Why to use factory pattern


I am trying to understand the Factory Method design pattern and i have come across multiple questions similar to the one on my mind but my question still remains unanswered.

this is the article I am referring in my question

In the example mentioned in above article why do we need a concrete factory of HtmlDialog and WindowsDialog and at the main method choose one of the implementations of Dialog, instead of directly choosing the implementation of Button from the available HtmlButton and WindowsButton


Solution

  • I think you're asking, why not do this:

    public class Demo {
        private static Button button;
    
        public static void main(String[] args) {
            configure();
            runBusinessLogic();
        }
    
        /**
         * The concrete factory is usually chosen depending on configuration or
         * environment options.
         */
        static void configure() {
            if (System.getProperty("os.name").equals("Windows 10")) {
                button = new WindowsButton();
            } else {
                button = new HtmlButton();
            }
        }
    
        static void runBusinessLogic() {
            button.render();
        }
    }
    

    The example is a little too simplistic to illustrate the benefit of the Dialog factory, so you're right to ask that.

    The idea is that you're not asking to render a button, you're asking to render a dialog which does something well defined. For example, you want a dialog which will prompt the user for a confirmation.

    By using a Dialog, Demo makes no assumptions about what the dialog will render, so Dialog subclasses are free to change their implementations. One implementation could create a button. One could create two buttons. One could use speech recognition to prompt the user. These details are all the "product".

    The Dialog factory hides all this from the calling code leaving the Dialog implementations free to decide how to render itself. The implementation can change from version to version and Demo still works.

    Again, this would be more apparent if Dialog was more than a thin wrapper around creating a button.