Template Methodパターン

スーパークラスで処理の枠組みを決め、実装の詳細をサブクラスに任せるパターン。呼び出し手順や共通処理をスーパークラスに実装する。

ニュアンスとしては「だいたい同じだけど、細かいところでいくつか違う」ものを実装するのに使える。

  • 例: 支払処理
package Payment;

use strict;
use Payment::CreditCard;
use Payment::Docomo;

sub pay {
    my ($user_id, $ammount, $method) = @_;
    my $payment;

    if ($method eq 'credit') {
        $payment = new Payment::CreditCard;
    } elsif ($method eq 'docomo') {
        $payment = new Payment::Docomo;
    } else {
        die 'select invalid value.';
    }

    my $c_ret = $payment->check($user_id, $ammount);
    if (! $c_ret->{has_credit}) {
        return 'You don\'t have enough credit.';
    }
    my $e_ret = $payment->execute($user_id, $ammount);
    if ($e_ret->{status}) {
        return 'Payment succeeded.';
    } else {
        return 'Payment failed.';
    }
}
sub check { }
sub execute { }
1;
package Payment::Docomo;

use strict;
use base qw(Payment);

sub new {
    my $class = shift;
    return bless({}, $class);
}

sub check {
    my $self = shift;
    my ($user_id, $ammount) = @_;
    # do something..
    $self->{has_credit} = 1;
    return $self;
}

sub execute {
    my $self = shift;
    my ($user_id, $ammount) = @_;
    # do something..
    $self->{status} = 1;
    return $self;
}
1;