美文网首页
(七)Stock

(七)Stock

作者: GoodTekken | 来源:发表于2023-03-26 08:14 被阅读0次
    #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

    相关文章

      网友评论

          本文标题:(七)Stock

          本文链接:https://www.haomeiwen.com/subject/mnpwrdtx.html