Bruso
Bruso

Reputation: 833

What is the best way to support nested object model in java?

I need to support UI client which has nested components. I have come up with below object model -

public class SomeUserInterface { 
        String name;
        List<Component> components;  
}
public class Component {
        List <Component> components;  
}

Here, SomeUserInterface will have multiple Components and each Component may have nested Components inside it. Is there any issue in the proposed object model? Or what is the best way to support nested components?

Note : SomeUserInterface and Component are not identical classes. SomeUserInterface can contain Component but vice-versa is not true.

Upvotes: 2

Views: 1532

Answers (1)

Cinnam
Cinnam

Reputation: 1922

Both Component and Container can contain components. If they offer the same methods for adding/removing etc., they should inherit from a common ancestor:

public class ComponentHolder {
    List<Component> components;
}

public class Component extends ComponentHolder {
    // ...
}

public class Container extends ComponentHolder {
    String containerName;
    // ...
}

EDIT: Another possibility would be to use composition. That way your classes wouldn't need a common ancestor, but would still use the same component-list implementation. If you decided to change the way components are stored, you would do it in one place only.

public class ComponentHolder {
    List<Component> components;
    // add, remove, get, ...
}

public class Component {
    ComponentHolder content;
    void add(Component c) {
        content.add(c);
    }
    // ...
}

public class Container {
    String containerName;
    ComponentHolder content;
    // ...
}

Upvotes: 1

Related Questions