カプセル化

プロパティ(データ)とメソッド(処理)を纏めることでそれぞれのオブジェクトを分けて管理する

'work/Module.pm'

# パッケージ名定義
package Module;
 
# プロパティ
my $price;
 
# コンストラクタ
sub new {
	# オブジェクトを取得
	my $class = shift;
 
	print "test-constract\n";
 
	# リファレンス
	my $ref = {};
	$ref->{price} = $price;
 
	# オブジェクト生成
	my $obj = bless $ref, $class;
 
	# オブジェクト返却
	return $obj;
}
 
 
# インスタンスメソッド
# プロパティpriceに値を設定
sub setPrice{
	my $obj = shift;
	my ($_price) = @_;
 
	$obj->{price} = $_price;
 
	print "test-method1\n";
 
}
 
# インスタンスメソッド
sub setPriceAdd{
	my $obj = shift;
 
	$obj->{price} = $obj->{price} * 10;
 
	print "test-method2\n";
 
}
 
# プロパティの値を出力
sub getDisplay{
	my $obj = shift;
	print $obj->{price} . "\n";
	print "test-method3\n";
}
 
# デストラクタ
sub DESTROY {
	# オブジェクトを取得
	my $obj = shift;
 
	# 処理
	print "test-descract\n";
 
}
 
# モジュール終端
1;
 
 

sample.pl

use strict;
use warnings;
 
# モジュール取り込み
use work::Module;
 
# メインスクリプト
my $obj = Module->new();
 
# プロパティに設定
$obj->setPrice(100);
$obj->setPriceAdd();
 
# プロパティの値を表示
$obj->getDisplay();
 
my $obj2 = Module->new();
 
# プロパティに設定
$obj2->setPrice(300);
$obj2->setPriceAdd();
 
# プロパティの値を表示
$obj2->getDisplay();
 
 
# 処理開始
BEGIN {
	print "test-script-start\n";
}
 
# 処理終了
END {
	print "test-script-end\n";
}
 
 

結果

>perl sample.pl
test-script-start
test-constract
test-method1
test-method2
1000
test-method3
test-constract
test-method1
test-method2
3000
test-method3
test-descract
test-descract
test-script-end
 
>
 
 



最終更新:2012年01月14日 21:46