Huy Vũ Quang

29 bundles
3 filesa month ago
1

Player.h

12345678910111213141516171819202122232425262728293031323334
#ifndef _PLAYER_H_ #define _PLAYER_H_ #include <memory> #include <string> class IPlayer { public: virtual std::string getName() const = 0; virtual std::string sendInstantMessage(std::string_view message) const = 0; }; class Player : public IPlayer { std::string mName; public: Player(std::string_view name); virtual std::string getName() const override; virtual std::string sendInstantMessage(std::string_view message) const override; }; class PlayerProxy : public IPlayer { public: PlayerProxy(std::unique_ptr<IPlayer> player); virtual std::string getName() const override; virtual std::string sendInstantMessage( std::string_view message) const override; private: std::unique_ptr<IPlayer> mPlayer; }; #endif

Player.cpp

1234567891011121314151617181920212223242526272829303132333435363738
#include <iostream> #include <sstream> #include "Player.h" using namespace std; bool hasNetworkConnectivity() { return true; } Player::Player(std::string_view name) { mName = name; } std::string Player::getName() const { return mName; } std::string Player::sendInstantMessage(std::string_view message) const { cout << "SENT. MESSAGE: " << message << endl; return rand() % 2 ? "yes" : "no"; } PlayerProxy::PlayerProxy(std::unique_ptr<IPlayer> player): mPlayer(std::move(player)) { } std::string PlayerProxy::sendInstantMessage(std::string_view message) const { if (hasNetworkConnectivity()) return mPlayer->sendInstantMessage(message); else throw std::runtime_error("No internet connection"); } std::string PlayerProxy::getName() const { return mPlayer->getName(); }

main.cpp

1234567891011121314151617181920212223242526
#include <iostream> #include "Player.h" using namespace std; bool informWinner(const IPlayer& player) { auto result = player.sendInstantMessage("You have won! Play again?"); if (result == "yes") { cout << player.getName() << " wants to play again." << endl; return true; } cout << player.getName() << " does not want to play again." << endl; return false; } int main() { srand(time(0)); PlayerProxy joeProxy(make_unique<Player>("Joe")); cout << joeProxy.getName() << endl; informWinner(joeProxy); return 0; }