CSC/ECE 517 Fall 2010/ch1 2c jp: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(42 intermediate revisions by the same user not shown)
Line 1: Line 1:
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]  The examples in this article will use the Ruby programming language.
First, we create a class called FairyTaleCharacter with one method defined to show the character's morality.  We assume all fairy tale characters are good people.  Next we create three instances of class FairyTaleCharacter:
  class FairyTaleCharacter
    def morality
      puts "I'm a good person!"
    end
  end
  pinocchio = FairyTaleCharacter.new
  robinHood = FairyTaleCharacter.new
  tinkerBell = FairyTaleCharacter.new
[[/code]]
module Flying
  def fly
    puts "I can fly!"
  end
end
tinkerBell.extend(Flying)
module Evil
  def morality
    puts "I'm evil!"
  end
end
wickedWitch = tinkerBell.clone()
wickedWitch.extend(Evil)
pinocchio.morality
robinHood.morality
tinkerBell.morality
wickedWitch.morality
tinkerBell.fly
wickedWitch.fly
In this example, we created three instances of class FairyTaleCharacter.  We then extending the object tinkerBell with the ability to fly.  At this point, we wish to create a fourth fairy tale character with the ability to flyThen we create a forth instance using the object tinkerBell as the prototype

Latest revision as of 14:34, 6 October 2010