|
Class::Object - each object is its own class |
Class::Object - each object is its own class
use Class::Object;
# Generate an object, give it a method called 'foo'
my $obj = Class::Object->new;
$obj->sub('foo', sub { return "FOO, I SAY!\n" });
# Generate another object, give it a different method called 'foo'.
my $another_obj = Class::Object->new;
$another_obj->sub('foo', sub { return "UNFOO!\n" });
# Get copies of those methods back out, just like any other.
my $obj_foo = $obj->can('foo');
my $another_foo = $another_obj->can('foo');
# Same names, same classes, different methods!
print $obj->foo; # "FOO, I SAY!"
print &$obj_foo; # "FOO, I SAY!"
print $another_obj->foo; # "UNFOO!"
print &$another_foo; # "UNFOO!"
print "Yep\n" if $obj->isa('Class::Object'); # Yep
print "Yep\n" if $another_obj->isa('Class::Object'); # Yep
# $obj->new clones itself, so $same_obj->foo comes out as $obj->foo
my $same_obj = $obj->new;
print $same_obj->foo; # "FOO, I SAY!"
Traditionally in OO, objects belong to a class and that class as
methods. $poodle is an object of class Dog and Dog might have methods
like bark(), fetch() and nose_crotch(). What if instead of the
methods belonging to the Dog class, they belonged to the $poodle
object itself?
That's what Class::Object does.
For the most part, these objects work just like any other. Things
like can() and isa() work as expected.
my $obj = Class::Object->new;
Generates a new object which is its own class.
my $clone_obj = $obj->new;
Generates a new object which is in the same class as $obj. They share their methods.
$obj->sub($meth_name, sub { ...code... });
This is how you declare a new method for an object, almost exactly like how you do it normally.
Normally you'd do this:
package Foo;
sub wibble {
my($self) = shift;
return $self->{wibble};
}
In Class::Object, you do this:
my $foo = Class::Object->new;
$foo->sub('wibble', sub {
my($self) = shift;
return $self->{wibble};
});
Only $foo (and its clones) have access to wibble().
This is just a proof-of-concept module. The docs stink, there's no real inheritance model... totally incomplete. Drop me a line if you'd like to see it completed.
DO NOT rebless a Class::Object object. Bad Things will happen.
Michael G Schwern <schwern@pobox.com>
the Class::Classless manpage is another way to do the same thing (and much more complete).
|
Class::Object - each object is its own class |