Composite

Many times, we come across structures that are comprised of leaf elements. However, the clients don't really care about this nature and want to behave with single (leaf) and composite structures in the same way. The expectation is that composites delegate the behavior to each constituent leaf.

The pattern can be visualized by this figure:

Here is some sample code in Golang:

type InterfaceX interface {
MethodA()
AddChild(InterfaceX)
}

type Composite struct{
children []InterfaceX
}

func (c *Composite) MethodA() {
if len(c.children) == 0 {
fmt.Println("I'm a leaf ")
return
}

fmt.Println("I'm a composite ")

for _, child:= range c.children {
child.MethodA()
}
}

func (c *Composite) AddChild(child InterfaceX) {
c.children = append(c.children, child)
}

The usage is shown as follows:

func test() {
var parent InterfaceX

parent = &Composite{}
parent.MethodA() // only a leaf and the print will confirm!

var child Composite
parent.AddChild(&child)
parent.MethodA() // one composite, one leaf
}
The code for composite implements the interface using pointer receivers because the AddChild method needs to mutate the struct.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset