class Program
{
static void Main(string[] args)
{
var atm = new AtmMachine();
var companyCard = new Card("Company Account", "1234");
try
{
atm.InsertCard(companyCard);
Console.WriteLine("Card '{0}' has been inserted, please enter PIN", atm.CurrentCardAccountName);
while (true)
{
var input = Console.ReadLine(); //validate input etc...
var validPin = atm.EnterPin(input);
if (validPin)
{
Console.WriteLine("Pin correct, start withdraw sequence");
//rest of the withdraw code here
break;
}
if (atm.MaxAttemptsReached)
{
Console.WriteLine("Max attempts reached, card blocked. Contact bank.");
atm.EjectCurrentCard();
break;
}
Console.WriteLine("PIN invalid, please try again");
}
atm.EjectCurrentCard();
}
catch (CardBlockedException ex)
{
Console.WriteLine(ex.Message);
atm.EjectCurrentCard();
}
Console.ReadLine();
}
}
public class AtmMachine
{
private const int MaxAttempts = 3;
private Card _currentCard;
private int _attempts;
public bool EnterPin(string pinCode)
{
if (pinCode == _currentCard.Pin)
return true;
_attempts++;
if (MaxAttemptsReached)
BlockCurrentCard();
return false;
}
public bool MaxAttemptsReached
{
get { return _attempts >= MaxAttempts; }
}
public string CurrentCardAccountName
{
get { return _currentCard.Account; }
}
public void InsertCard(Card card)
{
if (card.IsBlocked)
throw new CardBlockedException();
_currentCard = card;
_attempts = 0;
}
public void EjectCurrentCard()
{
_currentCard = null;
}
public void BlockCurrentCard()
{
_currentCard.Block();
}
}
public class CardBlockedException : Exception
{
public CardBlockedException()
: this("The card has been blocked")
{
}
public CardBlockedException(string message)
: base(message)
{
}
}
public class Card
{
private readonly string _account;
private readonly string _pin;
private bool _isBlocked;
public Card(string account, string pin)
{
_account = account;
_pin = pin;
}
public bool IsBlocked
{
get { return _isBlocked; }
}
public string Pin
{
get { return _pin; }
}
public string Account
{
get { return _account; }
}
public void Block()
{
_isBlocked = true;
}
}