diff --git a/README.md b/README.md index 9901bb8..a856a0a 100644 --- a/README.md +++ b/README.md @@ -1739,7 +1739,102 @@ the chain. #### Programmatic Example -TODO +Translating our account example above. First of all we have a base account +having the logic for chaining the accounts together and some accounts. + +```cpp +class Account +{ + public: + Account(void) + : name_("empty account"), balance_(0), successor_() + { + } + + void setNext(std::shared_ptr account) + { + successor_ = account; + } + + void pay(float amount) + { + if (canPay(amount)) { + std::cout << "Paid " << amount << " using " << name_ << "." + << std::endl; + balance_ -= amount; + } else if (successor_) { + std::cout << "Cannot pay using " << name_ << ". Proceeding ..." + << std::endl; + successor_->pay(amount); + } else { + std::cerr << "None of the accounts have enough balance." << std::endl; + } + } + + bool canPay(float amount) + { + return balance_ >= amount; + } + + protected: + std::string name_; + float balance_; + std::shared_ptr successor_; +}; + +class Bank : public Account +{ + public: + Bank(float balance) + { + name_ = "bank"; + balance_ = balance; + } +}; + +class Paypal : public Account +{ + public: + Paypal(float balance) + { + name_ = "paypal"; + balance_ = balance; + } +}; + +class Bitcoin : public Account +{ + public: + Bitcoin(float balance) + { + name_ = "bitcoin"; + balance_ = balance; + } +}; +``` + +Now let's prepare the chain using the links defined above (i.e., Bank, Paypal, +Bitcoin). + +```cpp +// We are going to create the chain: bank->paypal->bitcoin. + +// First, create the accounts. +std::shared_ptr bank = std::make_shared(100); +std::shared_ptr paypal = std::make_shared(200); +std::shared_ptr bitcoin = std::make_shared(300); + +// Next, establish the order. +bank->setNext(paypal); +paypal->setNext(bitcoin); + +// Let's try to pay using the first priority (i.e., the bank). +bank->pay(250); +// Output: +// Cannot pay using bank. Proceeding ... +// Cannot pay using paypal. Proceeding ... +// Paid 250 using bitcoin. +``` #### When To Use