Resource Manager A – Source Code

Header

#pragma once
#ifndef AVS_ICANOS_SYSTEM_RESOURCEMANAGERA_HPP
#define AVS_ICANOS_SYSTEM_RESOURCEMANAGERA_HPP

#include "Core.hpp"
#include "Exceptions.hpp"
#include <map>

namespace Icanos {
	namespace System {

		class Resource {
		public:
			virtual ~Resource() {}
		};

		class ResourceManagerA {
			typedef std::pair<URI, Resource*> ResourcePair;
			typedef std::map<URI, Resource*> ResourceList;

			ResourceList Resources;

		public:
			~ResourceManagerA() { UnloadAll(); }

			template <class S> URI& Load(URI& Uri);
			void Unload(URI& Uri);
			void UnloadAll();

			Resource* Get(URI& Uri);
			template <class T> T* Get(URI& Uri);
		};

	}
}

template <class S> Icanos::System::URI& Icanos::System::ResourceManagerA::Load(Icanos::System::URI& Uri)
{
	if (Resources.find(Uri) == Resources.end())
	{
		Resource* temp = new (std::nothrow) S(Uri);
		if (!temp)
			throw Exceptions::BadResourceAllocation();
		Resources.insert(ResourcePair(Uri, temp));
	}
	return Uri;
}

template <class T> T* Icanos::System::ResourceManagerA::Get(URI& Uri)
{
	Resource* temp = Get(Uri);
	if (temp != 0)
	{
		try {
			return dynamic_cast<T*>(Get(Uri));
		}
		catch (std::bad_cast) {

		}
	}
	return 0;
}

#endif

Source File

#include "ResourceManagerA.hpp"

void Icanos::System::ResourceManagerA::Unload(URI& Uri)
{
	ResourceList::const_iterator itr = Resources.find(Uri);
	if (itr != Resources.end())
	{
		delete itr->second;
		Resources.erase(Uri);
	}
}
void Icanos::System::ResourceManagerA::UnloadAll()
{
	ResourceList::iterator itr;
	for (itr = Resources.begin(); itr != Resources.end(); itr++)
		delete itr->second;
	Resources.clear();
}

Icanos::System::Resource* Icanos::System::ResourceManagerA::Get(URI& Uri)
{
	ResourceList::const_iterator itr;
	if ((itr = Resources.find(Uri)) != Resources.end())
		return itr->second;
	return 0;
}
  1. 06.03.2013 at 06:18 | #1

    Thank you for the source code, just what I was looking for, very helpful!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 72 other followers

%d bloggers like this: