mardi 3 novembre 2015

Java, Factory Pattern for dynamic style classes?

I have a library/android module that provides certain custom ui classes. (PanelView, GridView, TextView ...) All of these classes are stylable. Styles are parsed from text files into JSONObjects, organized in a StyleManager and from there retrieved and turned into a Styling object. The first idea would be something like

public class PanelView_Styling{
    public static PanelView_Styling createFromJSON(JSONObject data){...}
}

But then I cannot use an Interface for Stylings that includes a creation method. (No static methods in interface pre Java 8.)
The next alternative would be a factory

public class StylingFactory{
    public static Styling createStylingFromJSON(int stylingType, JSONObject data){
    switch( stylingType ){
        case 0: 
            /* get and validate attributes from data */
            /* return null or new Styling instance filled with the attributes */ 
        break; 
    }
}

The int typecheck is just an example. It could be a class reference, or enum, or even an attribute of the styling data or something different.
But the main problem with that approach is, that I cannot add new Stylings without changing the factory. When I use the ui module inside another one I will at some point have ExtendedPanelView and ExtendedPanelView_Styling. The Styling will have its own parameter validation logic, so I cannot just use reflection and copy everything from JSON into the Styling.

I think an abstract factory might be a solution. I would have a concrete factory for the basic ui elements and stylings already in the lib. Then I would have to implement a custom factory in each module that has additional ui elements and stylings. Then combine instances of the concrete factories under one instance and somehow figure out which factory is able to create stylings of which type. (Maybe just call each of them until one returns an object, or they all failed).
But this seems rather complicated. Is there a simpler, more straightforward approach to this problem?

Aucun commentaire:

Enregistrer un commentaire