(七)Stock

2023-03-26  本文已影响0人  GoodTekken
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Stock
{
    private:
        string name;
        int quantity;

    public:
        Stock(string name, int quantity)
        {
            this->name = name;
            this->quantity = quantity;
        }

        void buy()
        {
            cout << "买进:股票名称:"<< name << " , 数量:" << quantity << endl;
        }

        void sell()
        {
            cout<< "卖出:股票名称:"<< name << " , 数量:" << quantity << endl;
        }
};

class Order
{
    public:
        virtual void execute() = 0;
};

class BuyStock : public Order  //(1)
{
    private:
        Stock* stock;

    public:
        BuyStock(Stock* stock)
        {
            this->stock = stock;   //(2)
        }

        void execute()
        {
            stock->buy();
        }
};


class SellStock : public Order
{
    private:
        Stock* stock;

    public:
        SellStock(Stock* stock)
        {
            this->stock = stock;
        }

        void execute()
        {
            stock->sell();
        }
};

class Broker
{
    private:
        vector<Order*> orderList;

    public:
        void takeOrder(Order* order)   //(3)
        {
            orderList.push_back(order);
        }

        void placeOrders()
        {
            for(int i = 0; i < orderList.size(); i++)
            {
                orderList.at(i)->execute();  //(4)
            }
            orderList.clear();
        }
};

class StockCommand
{
    public:
        void main()
        {
            Stock* aStock = new Stock("股票A",10);
            Stock* bStock = new Stock("股票B",20);
            Order* buyStockOrder = new BuyStock(aStock);
            Order* sellStockOrder = new SellStock(bStock);
            Broker* broker = new Broker();
            broker->takeOrder(buyStockOrder);
            broker->takeOrder(sellStockOrder);
            broker->placeOrders();   //(5)
        }
};

int main()
{
    StockCommand* stockCommand = new StockCommand();
    stockCommand->main();
    delete stockCommand;
}

答案:
(1) public Order

(2) this->stock

(3) Order*

(4) orderList.at(i) 或 orderList[i] 或

(5) placeOrders

上一篇下一篇

猜你喜欢

热点阅读