What it amounts to is that every object method of such a class can also be used as a class method. Here is a minimal class that shows how to enable this feature.
This works, of course, because with this id() function the values of some_field for the generic object are stored in the same hash as the values for real objects, but keyed by the class name. Since the keys of real objects are integers in decimal, there is no conflict.package SomeClass; use Scalar::Util; # The traditional id() function is modified: for a non-ref, return # the argument, not undef sub id { Scalar::Util::refaddr( $_[ 0]) || shift } { # a field (attribute, object variable) with a read/write accessor my %some_field; sub some_field { my $obj = shift; $some_field{ id( $obj)} = shift if @_; $some_field{ id( $obj)}; } sub init { my $obj = shift; $some_field{ id( $obj)} = shift; $obj; } sub new { my $class = shift; bless( do{ \ my $o})->init( @_); } } package main; my $obj = SomeClass->new( 123); print $obj->some_field, "\n"; SomeClass->init( 456); print SomeClass->some_field, "\n";
With an un-modified id() function all such accesses would be keyed by the empty string, independent of the class (probably spewing warnings). It might appear to "work", but would break down with subclassing.
Another use would be in the implementation of singleton classes. Defining
would make sure that no real object (blessed ref) is created. Only the generic object (the invioking class) is ever returned by new().sub new { my $class = shift; $class->init( @_); }
I could contrive ther uses, but I'll stop here. I feel the feature has a certain neat-appeal, applications are secondary :)
Anno
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Generic object in inside-out classes
by stvn (Monsignor) on Feb 11, 2007 at 15:27 UTC | |
|
Re: Generic object in inside-out classes
by xdg (Monsignor) on Feb 11, 2007 at 13:31 UTC | |
by Anno (Deacon) on Feb 11, 2007 at 13:57 UTC | |
|
Re: Generic object in inside-out classes
by ysth (Canon) on Feb 11, 2007 at 06:27 UTC | |
by Anno (Deacon) on Feb 11, 2007 at 12:44 UTC | |
|
Re: Generic object in inside-out classes
by shmem (Chancellor) on Mar 19, 2007 at 12:04 UTC |