Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

(dkubb) Re: (1) Encapsulation through stringification - a variation on flyweight objects

by dkubb (Deacon)
on Apr 02, 2003 at 13:59 UTC ( [id://247492]=note: print w/replies, xml ) Need Help??


in reply to Encapsulation through stringification - a variation on flyweight objects

A couple of years ago I wrote a module that tried to implement the Flyweight pattern in perl, and submitted it for Code Review. I had originally planned to release it to CPAN, but reconsidered after I thought more about it. Looking at the code now, there wasn't much advantage to using my module versus just implementing it in modules that need it. Besides, my approach didn't really provide any real encapsulation of the data since it just returned the full data structure to the caller.

However, I still believe it can be a useful approach if data encapsulation is important to you.

In addition to the points Abigail-II identified (no garbage collection after the object goes out of scope, and inability to handle overload stringification) I'd like to add that you're $self doesn't need to be a blessed hash. Since you're only using the blessed hash's address when it's stringified as your object identifier inside the flyweight hash, you could use any type of blessed variable. In this case I'd recommend a simple blessed scalar, which would have less memory consumption and is cleaner IMHO.

Below is a sample class that deals with all three of the issues. It uses overload's StrVal() function to get the scalar's address, bypassing string overloading. (However, I'd only recommend doing this if you actually are using string overloading, for performance reasons):

package Flyweight; use strict; use overload (); { my %flyweight; sub new { my $self = bless \my $scalar => shift; # do other things to set up the object return $self; } sub get_attribute { my $self = shift; my $value = $flyweight{ overload::StrVal($self) }{attribute}; # do something to $value return $value; } sub set_attribute { my $self = shift; my $value = shift; # throw an exception if $value doesn't meet constraints $flyweight{ overload::StrVal($self) }{attribute} = $value; return; } # clean up the object when it goes out of scope sub DESTROY { delete $flyweight{ overload::StrVal(shift) } } } 1;

Dan Kubb, Perl Programmer

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://247492]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-03-28 08:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found