
LazyClass - An example metaclass with lazy initialization

package BinaryTree;
use metaclass 'Class::MOP::Class' => (
':attribute_metaclass' => 'LazyClass::Attribute'
);
BinaryTree->meta->add_attribute('$:node' => (
accessor => 'node',
init_arg => ':node'
));
BinaryTree->meta->add_attribute('$:left' => (
reader => 'left',
default => sub { BinaryTree->new() }
));
BinaryTree->meta->add_attribute('$:right' => (
reader => 'right',
default => sub { BinaryTree->new() }
));
sub new {
my $class = shift;
$class->meta->new_object(@_);
}
# ... later in code
my $btree = BinaryTree->new();
# ... $btree is an empty hash, no keys are initialized yet

This is an example metclass in which all attributes are created lazily. This means that no entries are made in the instance HASH until the last possible moment.
The example above of a binary tree is a good use for such a metaclass because it allows the class to be space efficient without complicating the programing of it. This would also be ideal for a class which has a large amount of attributes, several of which are optional.

Stevan Little <stevan@iinteractive.com>

Copyright 2006 by Infinity Interactive, Inc.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.