001    package topdown.service;
002    
003    import java.util.ArrayList;
004    import java.util.Iterator;
005    import java.util.List;
006    
007    /**
008     * An in-memory bank implementation.
009     */
010    public class BankMemDB implements Bank{
011    
012        /** The bank singleton. */
013        private static BankMemDB DB_INSTANCE = null;
014    
015        /** The list of accounts managed by this bank. */
016        private List m_accounts;
017    
018        /**
019         * Creates a bank instance.
020         */
021        private BankMemDB(){
022            m_accounts = new ArrayList(50);
023        }
024    
025        /**
026         * Provides access to the bank singleton.
027         * @return the bank instance.
028         */
029        public static BankMemDB newInstance(){
030            if(DB_INSTANCE == null){
031                DB_INSTANCE = new BankMemDB();
032            }
033            return DB_INSTANCE;
034        }
035    
036    
037        /**
038         * Adds a new account.
039         * @param name  the account owner's name.
040         * @param initBalance   the initial balance for the account.
041         * @return  the generated account ID.
042         * @throws AccountException if the initial balance is insufficent (<= 0).
043         */
044        public String addNewAccount(String name, float initBalance) throws AccountException {
045            Account newAccount = new Account(name,initBalance);
046            Iterator it = m_accounts.iterator();
047            while(it.hasNext()){
048                Account curAccount = (Account)it.next();
049                if(curAccount.getAccountID().equals (newAccount.getAccountID())){
050                    it.remove();
051                    break;
052                }
053            }
054            m_accounts.add(newAccount);
055            return newAccount.getAccountID();
056        }
057    
058        /**
059         * Returns the account that has the given ID.
060         * @param id    the account ID.
061         * @return  the account.
062         */
063        public Account getAccount(String id) {
064            Iterator it = m_accounts.iterator();
065            Account account = null;
066            while(it.hasNext()){
067                Account curAccount = (Account)it.next();
068                if(curAccount.getAccountID().equals(id)){
069                    account = curAccount;
070                    break;
071                }
072            }
073            return account;
074        }
075    
076        /**
077         * Returns a list of all account in the bank.
078         * @return  the list of accounts.
079         */
080        public List getAccounts() {
081            return m_accounts;
082        }
083    }