m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

Perlでオブジェクトサンプル(シングルトンパターン)

シングルトンパターン

モジュールでインスタンスを1つしか作成できないもの
データベースやファイルのポインタなどを使用する場合に使われる

ソース

sample.pl
#!/usr/bin/env perl

use strict;
use warnings;

use Sample::Test01;

my $obj = Sample::Test01::getInstance();
$obj->test1();

my $obj2 = Sample::Test01::getInstance();
$obj2->test1();

my $obj3 = Sample::Test01::getInstance();
$obj3->test1();

my $obj4 = Sample::Test01->new();
$obj4->test1();
lib
package Sample::Test01;

# インスタンス
my $obj = undef;

# new
sub new{
    if($obj == undef){
        my ($self) = @_;
        my $refs = {
            num => 0
        };
        my $obj = bless $refs, $self;
        return $obj;
    }else{
        return $obj;
    }
}

# インスタンスを生成
sub getInstance{
    if($obj == undef){
        $obj = Sample::Test01->new();
    }
    return $obj;
}

sub test1{
    my ($self) = @_;
    print "num = " . $self->{num} . "\n";
    $self->{num} = $self->{num} + 100;
}

#
1;

実行結果

$ perl -Ilib sample.pl
num = 0
num = 100
num = 200
num = 300
$

まとめ

基本、自分自身を内部で作成することは考えたことがないのでこんなことは新鮮。
複数のインスタンスを制御したくない場合に役に立つものですね