LazyClass - An example metaclass with lazy initialization


Moose documentation  | view source Contained in the Moose distribution.

Index


NAME

Top

LazyClass - An example metaclass with lazy initialization

SYNOPSIS

Top

  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

Top

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

Top

Stevan Little <stevan@iinteractive.com>

Yuval Kogman <nothingmuch@woobling.com>

COPYRIGHT AND LICENSE

Top


Moose documentation  | view source Contained in the Moose distribution.