Composite Pattern

The Composite pattern refers to structural design patterns.
Suppose we are developing an application – a photo album. The user can create folders, add photos there, and perform other manipulations. You definitely need the ability to show the number of files in folders, the total number of all files and folders.
Obviously, you need to use a tree, but how to implement the architecture of the tree, with a simple and convenient interface? The Composite pattern comes to the rescue.

Sheila in Moonducks

Next, in the Directory, we implement the dataCount () method – by passing through all the elements lying in the component array, adding all their dataCount’s.
Done!
Go example:

package main

import "fmt"

type component interface {
    
    dataCount() int
    
}

type file struct {
    
}

type directory struct {

    c []component

}

func (f file) dataCount() int {

    return 1

}

func (d directory) dataCount() int {
    
    var outputDataCount int = 0
    
    for _, v := range d.c {
        outputDataCount += v.dataCount()
    }
    
    return outputDataCount
    
}

func (d *directory) addComponent(c component) {

    d.c = append(d.c, c)

}

func main() {
    
    var f file
    var rd directory
    rd.addComponent(f)
    rd.addComponent(f)
    rd.addComponent(f)
    rd.addComponent(f)

    fmt.Println(rd.dataCount())
    
    var sd directory
    sd.addComponent(f)
 
    rd.addComponent(sd)
    rd.addComponent(sd)
    rd.addComponent(sd)
    
    fmt.Println(sd.dataCount())
    fmt.Println(rd.dataCount())

}

References

https://refactoring.guru/design-patterns/composite