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.
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.
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.
Ruby1class Engine 2 def start 3 puts "Engine starts" # Engine start message 4 end 5end 6 7class Wheels 8 def rotate 9 puts "Wheels rotate" # Wheel rotation message 10 end 11end 12 13class Seats 14 def adjust(position) 15 puts "Seats adjusted to position #{position}" # Seat adjustment message 16 end 17end 18 19class Car 20 def initialize 21 @engine = Engine.new 22 @wheels = Wheels.new 23 @seats = Seats.new 24 end 25 26 def start 27 @engine.start # Call to start engine 28 @seats.adjust('upright') # Adjust seat position 29 @wheels.rotate # Get wheels rolling 30 end 31end 32 33my_car = Car.new 34my_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.
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).
Fantastic work! You've now explored the concept of composition and successfully implemented it in Ruby! The next step involves engaging in exercises where you'll gain practical experience with composition in Ruby. Keep exploring, and continually practice to strengthen your understanding!