DEV Community

kroolar
kroolar

Posted on • Originally published at Medium

Ruby Design Patterns | PROTOTYPE ๐Ÿ‘

Overview

Prototype is 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 Prototype, 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).

Image description

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.

class Sheep
  attr_reader :genome, :name

  def initialize(name:)
    @name = name
    @genome = Random.new_seed
  end
end

molly = Sheep.new(name: 'Molly')
molly.genome # => 58277341567052563563790228364424051023

dolly = Sheep.new(name: 'Dolly')
molly.genome == dolly.genome # => false
Enter fullscreen mode Exit fullscreen mode

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 genome to the newly cloned sheep. To create a new clone, we will also have to enter a new name for our new sheep.

class Sheep
  attr_reader :genome
  attr_writer :name

  def initialize(name:)
    @name = name
    @genome = Random.new_seed
  end

  def clone(name:)
    new_sheep = dup
    new_sheep.name = name

    new_sheep
  end
end

dolly = molly.clone(name: 'Dolly')
molly.genome == dolly.genome # => true
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)