Singletonパターン

唯一のオブジェクトを生成をしたいケースで使う。

  • クラス
package Singleton;
use strict;
my $instance;
sub instance {
    my $class = shift;
    return $instance ||= bless {}, $class;
}
1;
  • 呼び出し
use Singleton;

my $instance1 = Singleton->instance();
$instance1->{who_am_i} = 'Kotaro';

my $instance2 = Singleton->instance();
$instance2->{who_am_i} = 'Ito';
print "$instance1->{who_am_i}\n"; # Ito
print "$instance2->{who_am_i}\n"; # Ito