in reply to Caching a default instance to avoid initializing it every time (with Moo)
I tend to do what Eily showed but there is also MooX::ClassAttribute–
BEGIN { package Catty; use Moo; use MooX::ClassAttribute; class_has "catcat" => is => "lazy", clearer => 1; # Sometimes desirable, like cache clearing. sub _build_catcat { my @them = qw( Abyssinian Balinese Chartreux Korat Nebelung Somali Tonkinese ); $them[rand@them]; } 1; } use Catty; my $catty = Catty->new; print $catty->catcat, $/; my $fat_catty = Catty->new; print $fat_catty->catcat, $/; Catty->clear_catcat; print $catty->catcat, $/; print $fat_catty->catcat, $/;
As for your question about design: a cached copy of something that is global to a process/env is fine. You can set it up to be readonly or have a private writer too for testing mock objects or something. You'd probably need to give details about what the design is and does to get solid advice on whether or not your case might have other, possibly better, options.
|
|---|