2017-06-20 20 views
2

我在c#中實現了一個銀行模塊,該模塊包含一個儲蓄賬戶,一個支票賬戶和一個簡單的儲蓄賬戶。所有賬戶都有一個所有者和一個餘額,所有賬戶都可以提取和存入資金,但不能從餘額中提取。直到這裏,非常容易。現在,我們的儲蓄賬戶有一個新的方法applyInterest和checkingsAccount方法deductFees和easySavinAccount都有。我想到的是使用抽象類帳戶:實現銀行模塊的最佳模型

public abstract class Account 
{ 
    protected string owner { get; set; } 
    //always use decimal especially for money c# created them for that purpose :) 
    protected decimal balance { get; set; } 
    public void deposit(decimal money) 
    { 
     if (money >= 0) 
     { 
      balance += money; 
     } 
    } 
    public void withdraw(decimal money) 
    { 
     if (money > balance) 
     { 
      throw new System.ArgumentException("You can't withdraw that much money from your balance"); 
     } 
     else balance -= money; 
    } 
} 

這將被所有3個類繼承。是否有適合以更好的方式實現這一點的設計模式?特別是對於easySaveAccount,組合可以提供幫助嗎?

謝謝!

回答

2

我建議

1.implement separate interfaces declaring the methods applyInterest and deductFees. 
2.You have already declared the abstract class Account. 
3.Now you can implement these interfaces in your classes for savings,checkings and easy saving account.All these classes should 
be implementing the abstract class. 
+0

這是一個很好的方法!這是四人幫的設計模式嗎?或者只是一個更好的實現方法? –

+0

我基於SOLID設計原理之一的接口隔離原理提出了這個建議。你可以從這裏得到一些想法:https://www.codeproject.com/Articles/822791/Developing-MVC-applications-using-SOLID -原則 – micky

0

我建議創建一個類Balance實現IBalance。所有帳戶可能只是將withdraw\deposit委託給該類別,因此他們沒有代碼重複,但您可以輕鬆地在其周圍添加一些附加邏輯(即納稅,授權,添加交易等)