利用C#中介面的繼承去模擬銀行的轉帳交易

iamzxf發表於2015-04-20


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace bankMoni
{
    public interface IBankAccount
    {
        void payIn(decimal amount);
        bool withdraw(decimal amount);
        decimal Balance { get; }
    }

    public interface ITransferBankAccount : IBankAccount
    {
        bool transferTo(IBankAccount des, decimal amount);
    }

    public class CurrentAccount : ITransferBankAccount
    {
        private decimal balance;

        public void payIn(decimal amount)
        {
            balance += amount;
        }

        public bool withdraw(decimal amount)
        {
            if (balance > amount)
            {
                balance -= amount;
                return true;
            }
            Console.WriteLine("餘額不足,請重試!");
            return false;
        }

        public decimal Balance {
            get { return balance; }
        }

        public bool transferTo(IBankAccount des, decimal amount)
        {
            bool result;

            if ((result = withdraw(amount)) == true) 
                des.payIn(amount);

            return result;
        }

        public override string ToString()
        {
            return String.Format("bank account, balance={0,6:C}",balance);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            IBankAccount bankacc = new CurrentAccount();
            ITransferBankAccount transbankacc = new CurrentAccount();

            bankacc.payIn(500);
            transbankacc.payIn(200);

            transbankacc.transferTo(bankacc,100);

            Console.WriteLine(bankacc.ToString());
            Console.WriteLine(transbankacc.ToString());

            Console.ReadLine();

        }
    }
}



相關文章