GOF Series: Episode #5 : [The Prototype Pattern] - In IronRuby
Firstly let me mention that whilst this series started out as demonstrating the Gang of Fours patterns in C# I have since decided to change direction a little bit and have the rest of the series presented in IronRuby. Why? My Reasons are twofold, firstly there are probably more than enough examples of the patterns in C# that another one will certainly not be missed and second completing the series in IronRuby will serve as great learning tool on the way to better knowing the language. I have previously posted on the Builder Pattern implemented in IronRuby and for that example I used Sapphire in Steel to develop the code and I am really hoping that we get a great code editor for IronRuby when it makes it’s official debut.
What purpose does this pattern serve?
Implementing the prototype pattern facilitates creating a prototypical object and subsequently being able to produce copies of that prototype.
Example Code:
First lets start with our Vehicle manager which will hold the prototyped vehicles that we wish to take copies of.
class VehicleManager def initialize @cars = {} end def add key, prototype @cars[key] = prototype end def remove key @cars.delete key end def get_vehicle_by_key key @cars[key].deep_copy end end
Next we create a module that we will use as a mixin to extend a ‘vehicles’ behaviour to include cloning.
module Cloneable attr_accessor :id attr_accessor :horse_power def deep_copy Marshal.load(Marshal.dump(self)) end end
class Car include Cloneable def initialize horse_power, id @id = id @horse_power = horse_power end end class MotorCycle include Cloneable def initialize horse_power, id @id = id @horse_power = horse_power end end
All that’s left is to look at how to create some prototype’s using these classes.
$counter = 1 #new up a VehicleManager to store vehicles #that we are interested in cloning vmanager = VehicleManager.new #add a car and motor cycle to the manager vmanager.add :eighty, Car.new(80, $counter) $counter += 1 vmanager.add :ninety , MotorCycle.new(90, $counter) #retrieve clones of the car and motor cycle vehicle_car = vmanager.get_vehicle_by_key :eighty vehicle_bike = vmanager.get_vehicle_by_key :ninety #print the results puts “The horse power for the car is “ + “#{vehicle_car.horse_power} and the ID is :#{vehicle_car.id}” puts “The horse power for the motor cycle is “ + “#{vehicle_bike.horse_power} and the ID is :#{vehicle_bike.id}”
No comments yet. Be the first.
Leave a reply








