Lesson Overview and Goals

Hello, welcome back! Today, we will delve into the fundamentals of Basic Design Patterns — specifically, Composition! A critical pattern in software design, composition helps us create complex types by combining simpler components using Go's structs and interfaces. Our journey today will explore the concept of composition, its value in software development, and how to implement it practically in Go.

Garnering Clarity on the Composition Design Pattern

To kick-start our exploration, let's understand Composition. In software design, composition refers to the way we combine simpler types into a more complex system using structs and interfaces in Go. For example, when constructing a car, we bring together components like the Engine, Wheels, and Seats. In composition, if the parent object (the car) ceases to exist, the encapsulated components generally cease to exist as well, reflecting real-world dependencies.

Acing the Composition Design in Go

Now, let's translate the theory into Go. We’ll show how a Car can be composed by encapsulating the Engine, Wheels, and Seats structs within it. The Car will own these components, and their lifecycles are managed within the Car.

package main

import (
    "fmt"
)

type Engine struct{}

func (e Engine) Start() {
    fmt.Println("Engine starts")
}

func (e Engine) Stop() {
    fmt.Println("Engine stops")
}

type Wheels struct{}

func (w Wheels) Rotate() {
    fmt.Println("Wheels rotate")
}

type Seats struct{}

func (s Seats) Adjust(position string) {
    fmt.Println("Seats adjusted to position", position)
}

type Car struct {
    engine Engine
    wheels Wheels
    seats  Seats
}

func (c *Car) Start() {
    c.engine.Start()     // Call to start engine
    c.seats.Adjust("upright") // Adjust seat position
    c.wheels.Rotate()    // Get wheels rolling
}

func main() {
    myCar := &Car{
        engine: Engine{},
        wheels: Wheels{},
        seats:  Seats{},
    }
    myCar.Start() // Begin car functions
}

// Prints:
// Engine starts
// Seats adjusted to position upright
// Wheels rotate

In the above code, the Car struct encapsulates the Engine, Wheels, and Seats structs, creating a composition pattern. These components are composed rather than subclassed, enabling reuse in different contexts.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal