Domanda

For example, suppose I have a class to create a button with specific styles common to my app, I can have either

  1. Return a new modified object:

    public class ButtonFactory {
        public static Button createAppButton(String st, int fontSize) {
            Button b = new Button();
            b.setColor(...);
            b.setText(...);
            b.playAnimation(...);
            return b;
        }
    }
    .
    .
    .
    Button b = ButtonFactory.createAppButton("test", 15);
    
  2. Modify exist button from outside:

    public class ButtonFactory {
        public static void modifyAppButton(Button b, String st, int fontSize){
            b.setColor(...);
            b.setText(...);
            b.playAnimation(...);
        }
    }
    .
    .
    .
    Button b = new Button();
    ButtonFactory.modifyAppButton(b, "test", 15);
    

Which one should I use?

È stato utile?

Soluzione

A factory by definition constructs things.

You should always name things based on what they do so that other programmers are not surprised by your code's behaviour.

Both of these classes are potentially useful, but if you called it a factory then it should construct and return instances

Altri suggerimenti

  • only the first class is a factory.

  • More importantly, I would not make the factory creator method static (or at least not call it that way). Unless you actually instantiate some object with an interface or use some other generic programming mechanism, this is a pointless ineffective use of the factory pattern. You need to be able to change factories somehow. A better representation for a factory would be a FUNCTION OBJECT (e.g. https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1) or std::function<> (in C++). That way, you can EITHER use a static function (most common case) - or a bound function (with data).

Consider some stylistic pattern for your buttons, like background color, shape, or some such. You could have this DEFAULT in your DEFAULT factory. But you could have different factories that fill in different defaults (maybe based on user settings).

If your button factory was an object, the default might be the one you provided in your example. But you could invoke the same code with a new factory that generated different values for those unspecified parameters.

Consider using a Prototype pattern instead. Establish the properties you'd generally want in a button, and then use it as a template for all others.

A factory method would only be useful here if you had several different types to choose from (and abstract factory if said creation itself was wildly different one from the next). Since you're producing a single Button, factory is probably unnecessary here.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top