Stevan Little > Class-MOP-0.26 > LazyClass

Download:
Class-MOP-0.26.tar.gz

Annotate this POD

CPAN RT

New  1
Open  1
View Bugs
Report a bug
Source   Latest Release: Class-MOP-0.37

NAME ^

LazyClass - An example metaclass with lazy initialization

SYNOPSIS ^

  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

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.

AUTHOR ^

Stevan Little <stevan@iinteractive.com>

COPYRIGHT AND LICENSE ^

Copyright 2006 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.