The composite design pattern, behold the power of interfaces!

The composite design pattern uses an interface to treat a collection of objects as a single object. You can spot a composite class because it implements an interface and possesses a collection of that same interface.

class MyComposite implements MyInterface
{
    private MyInterface[] my_interfaces = []

    public addMyInterface(MyInterface my_interface)
    {
        this.my_interfaces.add(MyInterface my_interface)
    }

    public doWork()
    {
        foreach(this.my_interfaces as my_interface)
        {
            my_interface.doWork()
        }
    }
}

MyComposite has a collection of MyInterface and calling doWork() iterates that collection and calls doWork() on each collection item.

Anywhere the interface is referenced, the composite can be used, so a single interface implementation can be replaced with a collection of implementations without modifying any calling code.

Behold the power of interfaces!

Home