Design Patterns in Ruby | PROTOTYPE

rubyhub.io
2 min readOct 31, 2022

--

A creational design pattern that allows you to create a copy of the object.

Real World Example

Sometimes the name Clone can be found instead of the name Protype, and this is what I will use for the example below because, in my opinion, it is more appropriate. So we probably all know the story of the first cloned sheep named Dolly(https://en.wikipedia.org/wiki/Dolly_(sheep)). But what does it mean she was a clone? Which means she was biologically the same as the sheep from which the cells were taken (let’s call her Molly).

Photo by Sam Carter on Unsplash

So, to create our clone (Dolly), we need two things:

  • The object we can clone(Molly)
  • A method that will allow us to clone this object(clone)

Coding Problem

First, let’s define a Sheep class that will allow us to create a new sheep.

As you can see in the example above, I used a special method that assigns a unique genome encrypted in the form of a sequence of 39 digits. At this point, we are unable to create objects with two identical genomes.

Solution

Using the Prototype pattern, we will add a clone method to our class that will allow us to clone our object. This method will be responsible for assigning the same genotype to the newly cloned sheep. To create a new clone, we will also have to enter a new name for our new sheep.

This method allows you to easily clone our sheep and give it a new name.

Caution

However, it should be remembered that in Ruby the Prototype pattern is implemented in the standard library, so when creating the clone method, we overwrite the existing one. In some cases, overriding this method can be useful because the default method only makes a shallow copy of the object.

More reading

--

--

rubyhub.io

[🔴 100% Follow-Back 🔴] I'm Full Stack Developer with 5-years of experience working with Ruby on Rails, trying to share my knowledge with others.