view api/Factories/WarFoundryFactoryFactory.cs @ 34:b28be912adab

Re #32 - Migrate to schema * Remove use of Categories (now just has a single category) * Fix infinite loop of trying to load files by adding a "is loading" flag * Fix invalid setting of MinSize to MaxNumber when we're testing if MinSize > MaxSize
author IBBoard <dev@ibboard.co.uk>
date Sun, 15 Mar 2009 16:07:52 +0000
parents a99d3b8466ba
children
line wrap: on
line source

// This file (WarFoundryFactoryFactory.cs) is a part of the IBBoard.WarFoundry.API project and is copyright 2009 IBBoard.
//
// The file and the library/program it is in are licensed under the GNU LGPL license, either version 3 of the License or (at your option) any later version. Please see COPYING.LGPL for more information and the full license.

using System;
using System.Collections.Generic;
using System.Reflection;
using IBBoard;
using IBBoard.Logging;

namespace IBBoard.WarFoundry.API.Factories
{
	public class WarFoundryFactoryFactory
	{
		private Dictionary<Type, IWarFoundryFactory> factories = new Dictionary<Type, IWarFoundryFactory>();
		private Type defaultType;
		private static WarFoundryFactoryFactory factoryFactory;
		
		private WarFoundryFactoryFactory()
		{
		}
		
		public static WarFoundryFactoryFactory GetFactoryFactory()
		{
			if (factoryFactory == null)
			{
				factoryFactory = new WarFoundryFactoryFactory();
			}
			
			return factoryFactory;
		}
		
		public IWarFoundryFactory GetFactory()
		{
			return GetFactory(DefaultType);
		}
		
		public IWarFoundryFactory GetFactory(Type cls)
		{
			cls = CheckType(cls);
			
			IWarFoundryFactory factory = null;	
			factories.TryGetValue(cls, out factory);
			
			if (factory == null)
			{
				factory = null;
				MethodInfo method = cls.GetMethod("GetFactory");
				
				if (method!=null)
				{
					LogNotifier.Debug(GetType(), "Found GetFactory method on " + cls.Name);
					object temp = method.Invoke(null, new object[]{});
					
					if (temp is IWarFoundryFactory)
					{
						factory = (IWarFoundryFactory)temp; 
						factories.Add(cls, factory);
					}
				}
			
				if (factory == null)
				{
					throw new ArgumentException("Could not create factory for class "+cls.FullName);
				}
			}
		
			return factory;
		}
		
		public Type DefaultType
		{
			get { return defaultType; }
			set {
				value = CheckType(value);
				defaultType = value;
			}
		}
		
		private Type CheckType(Type cls)
		{
			if (cls == null)
			{
				if (DefaultType!=null)
				{
					return DefaultType;
				}
				else
				{
					throw new InvalidOperationException("Class cannot be null when no default class is set");
				}
			}
			else if (!typeof(IWarFoundryFactory).IsAssignableFrom(cls))
			{
				throw new ArgumentException("Class "+cls.FullName+" was not a subtype of "+typeof(IWarFoundryFactory).FullName);
			}
			
			return cls;
		}
	}
}