模板模式

来源:互联网 发布:连接wifi成功但没网络 编辑:程序博客网 时间:2024/05/21 13:54

1 抽象类,提供模板


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;
    }

}

 2 模板之一设置

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


    
public double doCalculateInterestRate()
    
{
        
return 0.065D;
    }

}

 

3 模板之二的设置

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


    
public double doCalculateInterestRate()
    
{
        
return 0.045D;
    }

}

 

4 具体模板调用

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());
    }

}

 

run-single:
Interest earned from Money Market account = 325.935
Interest earned from CD account = 470.795

生成成功(总时间:0 秒)

原创粉丝点击