Lesson Overview and Goals

Hello, welcome to today's lesson! Today, we will uncover the principles of Revising Basic Design Patterns - Composition! Composition is a valuable component of software design patterns, enabling the creation of complex classes from simpler ones. Our focus today is on understanding the concept of composition, its importance in software development, and how to implement it effectively in Ruby.

Garnering Clarity on the Composition Design Pattern

Let's delve into the concept of Composition. In object-oriented programming (OOP), composition allows a class to include other classes, facilitating the development of sophisticated systems out of simpler components. For example, constructing a car involves combining various independent components like the engine, wheels, and seats — a real-life illustration of composition. It's important to note that in composition, if the parent object (the car) is destroyed, the child objects (the components) also cease to exist.

Acing the Composition Design in Ruby

Now, let's transform theory into practice with a Ruby implementation of the composition pattern. We'll model the previously mentioned car scenario by creating a Car class in Ruby that incorporates objects from the Engine, Wheels, and Seats classes. These child objects exist within the Car class, forming its components.

class Engine
  def start
    puts "Engine starts"  # Engine start message
  end
end

class Wheels
  def rotate
    puts "Wheels rotate"  # Wheel rotation message
  end
end

class Seats
  def adjust(position)
    puts "Seats adjusted to position #{position}" # Seat adjustment message
  end
end

class Car
  def initialize
    @engine = Engine.new
    @wheels = Wheels.new
    @seats = Seats.new
  end
  
  def start
    @engine.start  # Call to start engine
    @seats.adjust('upright')  # Adjust seat position
    @wheels.rotate  # Get wheels rolling
  end
end

my_car = Car.new
my_car.start  # Begin car functions

In this Ruby code, the Car class encapsulates Engine, Wheels, and Seats objects. These components are independent but integral parts of the Car class, embodying the Composition design pattern.

Discerning Composition From Inheritance

In OOP, Composition and Inheritance are two significant approaches to modeling relationships between classes. Whereas inheritance defines an "is-a" relationship, composition asserts a "has-a" relationship. For instance, a Car IS a Vehicle (Inheritance), but a Car HAS an Engine (Composition).

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