mardi 6 octobre 2020

How to create different instances using Singleton pattern?

I need to build a simple app like shopping cart.

main.cpp

int main()
{
    Cart cart;
    // add items
    cart.addItem("Shirt", ItemType:Clothing);
    cart.addItem("Xbox", ItemType::Entertainment);
    cart.addItem("Bowl", ItemType::Cooking);
    // print item
    cart.printItems();
    Item::destroy();
}

Item.h

enum ItemType
{
    Cooking,
    Clothing,
    Entertainment
};

class Item
{
private: 
    Item(const std::string& name, const ItemType& itemType);
    static Item* m_instance;
    std::string m_name;
    ItemType m_itemType;

public:
    static Item *getInstance(const std::string& name, const ItemType& itemType);    
    static void destroy();
    const std::string& getName() const;
    const ItemType& getItemType() const;
    void print() const;
};

Item.cpp

Item* Item::m_instance = nullptr;
Item::Item(const std::string& name, const ItemType& itemType)
{
    m_name = name;
    m_itemType = itemType;
}

Item* Item::getInstance(const std::string& name, const ItemType& itemType)
{
    if (!m_instance) {
        m_instance = new Item(name, itemType);
    }
    return m_instance;
}

void Item::destroy()
{
    delete m_instance;
    m_instance = nullptr;
}

void Item::print() const
{
    std::cout << "Item name: " << m_name << std::endl;
}

Cart.h

class Cart
{
public:
    Cart();
    ~Cart();

    void addItem(const std::string& name, const ItemType& itemType);
    void printItems();

private:
    std::vector<Item*> m_itemList = {};
};

Cart.cpp

void Cart::addItem(const std::string& name, const ItemType& itemType)
{
    Item *newItem = Item::getInstance(name, itemType);
    m_itemList.push_back(newItem);  
}

void Cart::printItems()
{
    std::cout << "Items" << std::endl;
    for (int i = 0; i < m_itemList.size(); i++)
    {
        m_itemList[i]->print();
    }
    std::cout << std::endl;
}

When I run this code, the result is

Item name: Shirt

Item name: Shirt

Item name: Shirt

what I need is

Item name: Shirt

Item name: Xbox

Item name: Bowl

I am learning design pattern. I know the purpose of that is to create only one instance. In this example I should use singleton pattern. But I do not know where I am wrong, so I receive this result. Could you tell me where I should correct in my code? Many thanks!

Aucun commentaire:

Enregistrer un commentaire