"be consistent" | |
PerlMonks |
Generic object in inside-out classesby Anno (Deacon) |
on Feb 10, 2007 at 20:50 UTC ( [id://599394]=perlmeditation: print w/replies, xml ) | Need Help?? |
With inside-out classes it can be arranged that the class itself behaves like an object, which I'll call its generic object. The generic object can be initialized and normal accessors can be used with it to set and retrieve values. It is, however, not a real object in the sense of a blessed reference. Different classes have (represent? are?) different generic objects.
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.
The modification is in the function id() used to get the reference address of an object when accessing data.
There are probably not too many uses for the generic object, but two come to mind. For one, often a place is wanted to store default values for all objects. The generic object offers itself as a class-wide template to hold such values.
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. 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(). I could contrive ther uses, but I'll stop here. I feel the feature has a certain neat-appeal, applications are secondary :) Anno
Back to
Meditations
|
|