How do you set specific properties to a class crea

2019-06-24 02:39发布

问题:

Is it possible to have concrete factories create concrete classes with type specific parameters for them, using the abstract factory pattern? Or do the different concrete classes created by their respective concrete factories need to to have the same fields?

Ex) In the image below how would you go about to instantiate the WinButton and the OSXButton with different set of arguments given by the client (Application)?

回答1:

One of the approaches to address such problems is to send object parameters. Example, in C# Object is the base class & you can pass parameter of type Object which can take any derived class. In the implementation, this object can be casted back to the desired derived type. Even specific properties can be set this way.



回答2:

This is not easy without having more details. One thing I would do, is to try to pass the arguments to constructor of the concrete factory class. For different arguments you would have to create different factory instance, which might not be the best solution, but as said, this depends on details.

Example:

    GUIFactory factory = new WinFactory(WIN_9x_THEME);
    Button greyButton = factory.createButton();
    factory = new WinFactory(WIN_VISTA_THEME, 50);
    Button semiTransparentButton = factory.createButton();