Perl6 Object Oriented Cookbook (v0.2.1)  
Section 3: Working with Classes  
 
Recipe 3.13: Creating 'Classless' Object Hierarchies
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
5.00 Rating, 2 Votes  

How acceptable is the proposed solution?
  (Login to Vote)
5.00 Rating, 2 Votes  

Problem:  

You want to create a hierarchy of classless objects.

Solution:  

Use the as subclass transformation to create object instances that inherit from other object instances. Make sure the base class has been declared is autovivifying, so that instances can add whatever attributes and methods they need:

class MyClass is autovivifying { ... }   # a base class to start from.
my $obj = MyClass.new;                   # create our 'root' object

my $aClass = $obj as subclass;           # make an object that inherits from $obj
   $aClass.foo = 'a';                    # add an attrib called 'foo', init to 'a'

my $bClass = $aClass as subclass;        # make an object that inherits from $foo
   $bClass.foo = 'b';                    # overrides the $aClass implementation of 'foo'
   $bClass.bar = method { ... };         # and adds a new method

print "true" if $bClass isa $aClass;     # prints 'true'
print $aClass.foo;                       # prints 'a'
print $bClass.foo;                       # prints 'b'

Discussion:

Some languages have the concept of instance-based inheritance, in which objects aren't well-defined classes so much as extensions of other object instances. A root object is used as the base of the inheritance chain, and all other objects are created as empty objects inheriting from that root object. (This approach is available in perl5 via the CPAN module Class::Classless, by Sean Burke.)

This is a powerful approach for situations where you don't have complete information about all the behaviors that will be expected of each object, or where there are so many possible combinations of object behavior that declaring a class for each possible combination is impractical.

Note that classless objects in perl6 aren't really classless -- they are instances of the class that was used to create the root object.

Issue: This approach is somewhat different from that presented in recipe 4.4, "Inheriting from Object Instances". They need to be reconciled.


Log In to Comment


Login / Edit User Info -- Copyright © 2002 Cognitivity -- Previous Page   Next Page