模板方法模式的一个例子

 11.1 模板方法例子 

      考虑一个银行存款例子。假设系统需要支持两种存款账号,及货币市场账号(MoneyMarketAccount  )和定期存款账号(CDAccount)。这两种账号的存款利息是不同的,因此在计算一个存户存款利息的时候,必须区分两种不同的账号。
      这个系统的总行为是计算出利息,这个也就决定了两个步骤:一是确定账号类型,二是确定利息的百分比。因此系统需要两个基本方法:一个计算账号类型,一个计算利息百分比。

 

      代码实现:

    

package test.biancheng.patterns.template.example1;

abstract public class Account
{
    protected String accountNumber;

    public Account()
    {
		accountNumber = null;
    }

    public Account(String accountNumber)
    {
        this.accountNumber = accountNumber;
    }

    final public double calculateInterest()
    {
        double interestRate = doCalculateInterestRate();
        String accountType = doCalculateAccountType();
        double amount = calculateAmount(accountType, accountNumber);

	   	return amount * interestRate;
    }
                                    
    abstract protected String doCalculateAccountType() ;

    abstract protected double doCalculateInterestRate() ;

    final public double calculateAmount(String accountType, String accountNumber)
    {
        //retrieve amount from database...here is only a mock-up
        return 7243.00D;
    }
}

 

public class CDAccount extends Account 
{
    public String doCalculateAccountType()
    {
        return "Certificate of Deposite";
    }

    public double doCalculateInterestRate()
    {
        return 0.065D;
    }
}

 

public class MoneyMarketAccount extends Account 
{
    public String doCalculateAccountType()
    {
        return "Money Market";
    }

    public double doCalculateInterestRate()
    {
        return 0.045D;
    }
}

 

public class Client
{
    private static Account acct = null;

    public static void main(String[] args)
    {
    	acct = new MoneyMarketAccount();
        System.out.println("Interest earned from Money Market account = " + acct.calculateInterest());

    	acct = new CDAccount();
        System.out.println("Interest earned from CD account = " + acct.calculateInterest());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值