Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <unordered_map>
- static size_t indexAsset = 0;
- struct Image
- {
- int _w;
- int _h;
- };
- struct Asset
- {
- int _id = 0;
- std::string _name;
- Asset()
- {
- _id = indexAsset;
- ++indexAsset;
- }
- ~Asset()
- {
- std::cout << "- Delete Asset : "<< _name << "\n";
- }
- };
- struct Bitmap : public Asset
- {
- Image *_data = nullptr;
- Bitmap(std::string name, int w, int h)
- {
- _name = name;
- _data = new Image{w,h};
- }
- ~Bitmap()
- {
- if (_data != nullptr)
- delete _data;
- }
- Image *getData()
- {
- return _data;
- }
- };
- struct Font : public Asset
- {
- Font(std::string name)
- {
- _name = name;
- }
- ~Font()
- {
- }
- };
- struct AssetManager
- {
- std::unordered_map<std::string, Asset*> _mapAsset;
- ~AssetManager()
- {
- if (!_mapAsset.empty())
- {
- auto it = _mapAsset.begin();
- while (it != _mapAsset.end())
- {
- if (it->second != nullptr)
- {
- delete it->second;
- it->second = nullptr;
- //it = _mapAsset.erase(it);
- }
- ++it;
- }
- _mapAsset.clear();
- }
- }
- void add(Asset *content)
- {
- _mapAsset.insert(std::pair<std::string, Asset*>(content->_name, content) );
- }
- bool del(std::string name)
- {
- auto it = _mapAsset.find(name);
- if (it == _mapAsset.end())
- {
- std::cout << "Not found : "<< name << "\n";
- return false;
- }
- if (it->second != nullptr)
- {
- delete it->second;
- it->second = nullptr;
- }
- _mapAsset.erase(it);
- //std::cout << "item found : "<< name << "\n";
- return true;
- }
- template <class C>
- C *get(std::string name)
- {
- auto it = _mapAsset.find(name);
- if (it != _mapAsset.end())
- return static_cast<C*>(it->second);
- return nullptr;
- }
- void showAll()
- {
- auto it = _mapAsset.begin();
- while (it != _mapAsset.end())
- {
- if ((*it).second != nullptr)
- std::cout << "[ "<< it->second->_name << " id = " << it->second->_id << " ]\n";
- ++it;
- }
- }
- };
- int main()
- {
- AssetManager _assetBank;
- _assetBank.add(new Bitmap("Mugen", 640, 360));
- _assetBank.add(new Font("mainFont"));
- _assetBank.add(new Bitmap("Silver", 480, 160));
- _assetBank.showAll();
- Bitmap *myImage = nullptr;
- myImage = _assetBank.get<Bitmap>("Mugen");
- std::cout << myImage->_data->_w << "\n";
- Font *myFont = _assetBank.get<Font>("mainFont");
- std::cout << "myFont name = " << myFont->_name << "\n";
- _assetBank.del("Silver");
- _assetBank.showAll();
- // if (myImage)
- // delete myImage;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement