Creating a simple Class Factory in C#

This is a simple class factory that will create and store instances of your objects on a “stack” and allow you to pull them off the stack when needed, kind of enforcing a singleton pattern.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Factory{

    public static class ClassFactory {

        private static Dictionary<object, object> _mapping = new Dictionary<object, object>();
        private static List<object> _instances = new List<object>();

        /// <summary>
        /// Adds a new instance of the specified type into the Factory
        /// </summary>
        /// <typeparam name="T">Type to add</typeparam>
        /// <param name="args">default parameters for type constructor</param>
        public static void Add<T>(params object[] args) {
            if (!_instances.Contains(typeof(T))) {
                object newInstance = Activator.CreateInstance(typeof(T), args);
               _instances.Add(newInstance);
            }
        }

        /// <summary>
        /// Mapped types must share an interface.
        /// </summary>
        /// <param name="Request"></param>
        /// <param name="Give"></param>
        public static void MapsTo(object Request, object Response) {
            if (!_mapping.ContainsKey(Request)) {
                _mapping.Add(Request, Response);
                if (!_instances.Contains(Request)) { _instances.Add(Request);}
                if (!_instances.Contains(Response)) { _instances.Add(Response); }
            } else {
                _mapping[Request] = Response;
            }
        }

        /// <summary>
        /// A new instance if T is created and stored on a stack, if a subsequent request for the same type is
        /// requested then the version created on the stack is created.
        /// </summary>
        /// <typeparam name="T">Type to create</typeparam>
        /// <param name="args">constructor parameters</param>
        /// <returns>requested type instance</returns>
        public static T Get<T>(params object[] args)
             where T : class {
            object outputInstance;
            string ResolveType = string.Empty;

            try {

                //Test mappings
                KeyValuePair<object, object> map = _mapping.SingleOrDefault(m => m.Key.GetType().Name == typeof(T).Name);
                if (map.Key != null) {
                    if (_instances.Find(t => t.GetType().Name == map.Value.GetType().Name) != null) {
                        var _tmp = _instances.Find(t => t.GetType().Name == map.Value.GetType().Name);
                        outputInstance = map.Value;
                    } else {
                        lock (_instances) {
                            object newInstance = Activator.CreateInstance(map.Value.GetType(), args);
                            _instances.Add(newInstance);
                            outputInstance = newInstance;
                        }
                    }
                    return (T)outputInstance;
                } else {
                    if (_instances.Find(t => t.GetType().Name == typeof(T).Name) != null) {
                        var _tmp = _instances.Find(t => t.GetType().Name == typeof(T).Name);
                        outputInstance = _tmp;
                    } else {
                        lock (_instances) {
                            T newInstance = (T)Convert.ChangeType(Activator.CreateInstance(typeof(T), args), typeof(T));
                            _instances.Add(newInstance);
                            outputInstance = newInstance;
                        }
                    }
                    return (T)outputInstance;
                }
            } catch (TargetInvocationException ex) {
                throw new TargetInvocationException(string.Format("Unable to create requested type {0}", typeof(T).Name), ex);
            }
        }

        /// <summary>
        /// Removes a specific type from the Factory
        /// </summary>
        /// <typeparam name="T">Type to remove</typeparam>
        /// <returns>true/false indicating if the removal was successful</returns>
        public static bool Kill<T>()
            where T : class, new() {
            if (_instances.Find(t => t is T) != null) {
                _instances.Remove(typeof(T));
                foreach (KeyValuePair<object, object> map in _mapping) {
                    if (map.Key.GetType().Name == typeof(T).Name){
                        _mapping.Remove(map.Key);
                    }
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// Removes all references from the Factory
        /// </summary>
        /// <returns>true/false indicating if the removal was successful</returns>
        public static bool KillAll() {
            try {
                _instances.ForEach(o => _instances.Remove(o));
                foreach (KeyValuePair<object, object> map in _mapping) {
                    _mapping.Remove(map.Key);
                }
            } catch {
                return false;
            }
            return true;
        }
    }

}

To add something to the stack you do this

ClassFactory.Add<MyClass>();

to get something from the stack you do this

MyClass myinstance = ClassFactory.Get<MyClass>();

26 Comments

  1. Here are a couple clash of clans hack tool keys you have to see to be a convincing boss:.
    Many games that are for consoles have PC or other versions out there, so don’t limit
    yourself to only console gaming. It is easy to hire
    an i – Phone developer or an Android developer today and making useful and quality applications are so much
    easier today.

  2. I feel like I’m continually trying to find fascinating things to
    find out about a variety of subjects, but I have the ability to
    include your blog among what i read every single day mainly because you’ve got powerful entries
    that I enjoy. Hoping there are much more amazing material coming!

    Feel free to surf to my web site: dentist orlando emergency (Rodger)

  3. I think the admin of this web page is actually working hard in favor of his web site, because here every stuff is quality
    based stuff.

    Look at my blog post … Iso certification in abu dhabi (Latasha)

  4. Greetings from Idaho! I’m bored to tears at work so I decided to browse your site on my iphone during lunch break.

    I enjoy the info you provide here and can’t wait to take
    a look when I get home. I’m surprised at how quick your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyways, fantastic blog!

  5. After devoting a healthy amount of time to actually playing the game
    and developing an attack style one can understand
    why this game is so popular. Figure out a schedule for how frequently you switch slots.
    This simulation game has an original storyline from the anime TV series but includes many familiar characters from the show and
    is heavily based off clash of clans hack no survey Hajime Isayama’s manga.

  6. I have been exploring for a little for any
    high-quality articles or blog posts in this sort of area .
    Exploring in Yahoo I ultimately stumbled upon this site.
    Studying this info So i am satisfied to show that I have an incredibly
    just right uncanny feeling I came upon just what I needed.

    I most certainly will make sure to do not forget this site and provides it a look on a constant basis.

    Feel free to visit my website – destiny strange Coins locations

  7. I’ve been browsing on-line more than 3 hours as of late,
    but I by no means found any attention-grabbing article like
    yours. It’s beautiful worth enough for me. Personally, if all site owners and bloggers made excellent content
    as you did, the net will be a lot more helpful than ever before.

  8. you’re actually a good webmaster. The site loading velocity is incredible.
    It kind of feels that you are doing any distinctive trick.
    Furthermore, The contents are masterwork. you have performed a excellent process on this topic!

    Feel free to surf to my weblog – Gta money Glitch

  9. Excellent post. I was checking continuously this blog and I am inspired!
    Extremely useful information specially the
    last section 🙂 I care for such info much. I was looking for
    this certain information for a long time. Thank you and
    good luck.

    my web blog; Adele Hello – Jimmie

  10. I got this web site from my friend who informed me regarding this web page and
    at the moment this time I am visiting this web page
    and reading very informative articles or reviews here.

    Also visit my page; gta 5 money glitch after patch 1.30 – youtube.com

  11. Wonderful items from you, man. I have consider your stuff prior
    to and you are simply extremely great. I really like what you have got right here,
    really like what you’re saying and the way wherein you are
    saying it. You make it enjoyable and you continue to care for to
    keep it smart. I can’t wait to read much more
    from you. That is really a great site.

    My webpage … Efren

  12. Howdy would you mind letting me know which webhost you’re working with?

    I’ve loaded your blog in 3 different internet browsers and I
    must say this blog loads a lot quicker then most. Can you suggest
    a good hosting provider at a fair price? Thanks a lot, I appreciate it!

Comments are closed.