NAME

LazyClass - An example metaclass with lazy initialization

SYNOPSIS

package BinaryTree;

use metaclass (
    ':attribute_metaclass' => 'LazyClass::Attribute',
    ':instance_metaclass'  => 'LazyClass::Instance',      
);

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

DESCRIPTION

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.

AUTHORS

Stevan Little <stevan@iinteractive.com>

Yuval Kogman <nothingmuch@woobling.com>

COPYRIGHT AND LICENSE

Copyright 2006-2008 by Infinity Interactive, Inc.

http://www.iinteractive.com

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.