CSC/ECE 517 Fall 2010/ch1 2c jp
Prototype-based object oriented programming is the method in which object behavior is defined by existing objects (or prototypes), not classes. In prototype-based programming (also called instance-based programming) prototypes are cloned to create extension objects.[1][4] Programmers then define the differences between the default behavior inherited from the prototype to create additional functionality for the extension object.[4]
All extension objects contain two parts: a list of pointers to their prototype objects, and a set of instructions unique to itself. When a method invocation is sent to an extension object, the object first looks to see if the method is defined in its own set of instructions. If the method is not found within the objects own code, it then looks for the method among the object's prototype methods, and so on. This system of method invocation is called delegation. Programming languages without delegation cannot implement prototype-based programming.[4]
Many programming languages, such as JavaScript, Self, Io, NewtonScript, Omega, Cecil, Lua, Object-Lisp, Examplars, Agora, ACT-I, Kevo, Moostrap, Obliq, and Garnet, allow for prototype-based inheritance.[5] The examples in this article will use the Ruby programming language.
In Ruby, you can define an extension object's prototype by using the SimpleDelegator class. In order to use the SimpleDelegator class you must include the delegate file. In this example we create two instances of class Polygon:
require 'delegate' class Polygon attr_reader :sides def initialize(sides) @sides = sides end end quadrilateral = Polygon.new(4) triangle = Polygon.new(3)
Next we create an extension object called rectangle using quadrilateral as our prototype. As I said before, we use the SimpleDelegator class and pass the prototype as the constructor argument:
rectangle = SimpleDelegator.new(quadrilateral) puts rectangle.sides # => 4
To add functionality in our inheritance hierarchy we use the extend method. The extend method will add functionality to a particular instance of a class:
module Area def area(length, width) length * width end quadrilateral.extend(Area) puts rectangle.area(10, 20) # => 200
According to the definition of delegation, if the method invoked is not part of the calling object then it attempts to find the method in the prototype object. Since the area method is not a part of the rectangle object the program then looks for the method in the prototype, quadrilateral.
The extend method only adds the functionality to the particular object it is invoked on, not to the class of that object. The object "quadrilateral" is an instance of class Polygon and so is the object "triangle". If the object "quadrilateral" is extended with the Area module then it will have access to the area method but the object "triangle" will not.
triangle.area(10, 20) # => ERROR