Composite Design Pattern
Learn how the Composite design pattern is implemented in Kotlin, and get to know about secondary constructors.
We'll cover the following...
Composite literally means made up of various elements or parts. The pattern allows us to treat the whole and the individual parts as one. Formally, the composite pattern is defined as composing objects into tree structures to represent part-whole hierarchies, thus letting clients uniformly treat individual objects and the composition of objects.
Let’s imagine we want to build a system to manage different kinds of troopers for the Galactic Empire.
We’ll start with an interface:
interface Trooper {fun move(x: Long, y: Long)fun attackRebel(x: Long, y: Long)}
There are different types of troopers like StormTrooper
, ShockTrooper
, and ScoutTrooper
etc.
And we can create multiple implementations for different types of troopers:
class StormTrooper : Trooper {override fun move(x: Long, y: Long) {// Move at normal speed}override fun attackRebel(x: Long, y: Long) {// Missed most of the time}}class ShockTrooper : Trooper {override fun move(x: Long, y: Long){// Moves slower than regular StormTrooper}override fun attackRebel(x: Long, y: Long) {// Sometimes hits}}
Now lieutenants of the Empire discover that no matter how well equipped, stormtroopers cannot hold their ground against the rebels because they are uncoordinated.
To provide better coordination, the Empire decides to introduce the concept of a squad for the stormtroopers. A squad should contain one or more stormtrooper of any kind, and when given commands, it should behave exactly as if it was a single unit.
The Squad
class therefore consists of a collection of stormtroopers:
class Squad(val units: List<Trooper>)
Let’s add a ...