Search code examples
javadesign-patternsumlcomposite

Can the Composite Design pattern avoid a Collection (List, HashTable) data structure?


I want a full comprehension of all possible types of the Composite Design Pattern when looking at code. In this code I have a composite object PeanutButterAndJellySandwich which contains Bread, PeanutButter and Jelly.

The reason PeanutButterAndJellySandwhich's field variables are all of type food is to account calories

interface Food{
    int calories = 9000;
}


class Bread implements Food{
    private String flour;
    private String salt;

}

class Jelly implements Food{
    private String fruit;
    private String sugar;
}

class PeanutButter implements Food{
    private boolean crunchy;
}

class PeanutButterAndJellySandwich implements Food{
    private Food bread;
    private Food jelly;
    private Food peanutButter;

    public void setBread(Bread bread){this.bread=bread;}
    public void setJelly(Jelly jelly){this.jelly=jelly;}
    public void setPeanutButter(PeanutButter butter){this.peanutButter=butter;}
}

Is this follow the Composite Design Pattern or does PeanutButterAndJellySandwhich need something like foodItems:ArrayList<Food>. The UML Diagram would look very similar.

UML Diagram

I ask this because I have not found this anywhere explicitly stated after about 5 hours of searching and in the application of something like an embedded system we may not want a collection data structure since memory/storage is limited. However, all examples online are utilizing many forms of lists.


Solution

  • From my understanding, composite pattern is meant to allow you ignore the difference between components (Bread, Jelly, PeanutButterAndJellySandwich, etc in your case) and their hierarchy, using runtime polymorphism most likely. It's meant to let you handle them in a uniformed way (through a loop, most likely), and let the runtime do the rest.

    Therefore, since your example just didn't show this intention and manually handled that, I would say this is not a composite pattern, but rather a plain (plan of) use of runtime polymorphism.

    However, your code does catch the point where PeanutButterAndJellySandwich is a Food, enabling the potential future use (e.g. a PeanutButterAndJellySandwich with an ingredient PeanutButterAndJellySandwich) which is the aim of the composite pattern. (But you didn't show this intention in your code.)


    p.s.

    1. But design patterns are not something sacred. They are meant as a guide rather than a restriction.

    2. I would say the question itself doesn't make much sense, because design patterns are not meant to save memory, but to promote good system designs. So they are described in a generic way for easier to describe and understand.