示例#1
0
 public VendingMachine(IDispenseProduct dispenser)
 {
     _dispenser      = dispenser;
     _productStock   = _productCatalog.Keys.ToDictionary(k => k, s => 0);
     _coinStock      = new CoinBag(_weightToValueMap);
     _currentMessage = GetDefaultMessage();
 }
示例#2
0
 private void VerifyCoinBagsAcceptSameTypes(CoinBag otherBag)
 {
     if (!_coinQuantities.Keys.OrderBy(x => x).SequenceEqual(otherBag._coinQuantities.Keys.OrderBy(x => x)))
     {
         throw new InvalidOperationException("these bags map to different coin types");
     }
 }
示例#3
0
        public CoinBag Without(CoinBag otherBag)
        {
            VerifyCoinBagsAcceptSameTypes(otherBag);
            var amounts = _coinQuantities.ToDictionary(x => x.Key, x => Math.Max(x.Value - otherBag._coinQuantities[x.Key], 0));

            return(new CoinBag(_valueMap, amounts));
        }
示例#4
0
        public CoinBag Merge(CoinBag otherBag)
        {
            VerifyCoinBagsAcceptSameTypes(otherBag);

            var amounts = _coinQuantities.ToDictionary(x => x.Key, x => x.Value + otherBag._coinQuantities[x.Key]);

            return(new CoinBag(_valueMap, amounts));
        }
示例#5
0
        public void SelectProduct(string productCode)
        {
            productCode = SanitizeProductCode(productCode); //Postel's Law ;-)

            if (!_productCatalog.ContainsKey(productCode))
            {
                return;
            }

            if (_productStock[productCode] <= 0)
            {
                _currentMessage = "SOLD OUT";
                return;
            }

            var productPrice = _productCatalog[productCode];

            _currentMessage = string.Format("PRICE {0:C}", productPrice);

            var currentAmount = GetCurrentAmount();

            if (currentAmount < productPrice)
            {
                return;
            }

            var changeDue = currentAmount - productPrice;

            var coinStockAndInserted = _coinStock
                                       .WithCoins(_coinsInserted);

            if (!coinStockAndInserted.CanMakeChange(changeDue))
            {
                _currentMessage = "EXACT CHANGE ONLY";
                return;
            }

            var coinsToReturn =
                coinStockAndInserted
                .MakeChange(changeDue);

            _coinStock = coinStockAndInserted.Without(coinsToReturn);
            _coinsInserted.Clear();
            _currentMessage = "THANK YOU";
            _dispenser.DispenseProduct(productCode);
            _coinReturn.AddRange(coinsToReturn.ToCoins());
        }
示例#6
0
 public void StockCoins(IDictionary <double, int> coinQuantities)
 {
     _coinStock      = new CoinBag(_weightToValueMap, coinQuantities);
     _currentMessage = GetDefaultMessage();
 }