Skip to content

Instantly share code, notes, and snippets.

@akx
Created November 5, 2012 20:20
Show Gist options
  • Save akx/4020123 to your computer and use it in GitHub Desktop.
Save akx/4020123 to your computer and use it in GitHub Desktop.
Abstract Singleton Cache Factory, C# flavor
/* 5.11.2012 22:08 */
using System;
using System.Collections.Generic;
namespace ServiceManager
{
public static class ServiceManager
{
private static Dictionary<Type, ServiceBase> _cache = new Dictionary<Type, ServiceBase>();
public static ServiceType Get<ServiceType>(string context) where ServiceType: ServiceBase, new() {
var t = typeof(ServiceType);
ServiceBase inst;
if(!_cache.TryGetValue(t, out inst)) {
_cache[t] = inst = new ServiceType();
}
inst.SetContext(context);
return (ServiceType)inst;
}
}
public abstract class ServiceBase
{
public abstract void SetContext(string context);
public ServiceBase() {
Console.WriteLine("FYI: New " + GetType().Name + " was born.");
}
}
public class AwesomeService: ServiceBase
{
private string _context = "none";
public override void SetContext(string context) {
_context = context;
}
public void ShoutThineContext() {
Console.WriteLine("LET IT BE KNOWN THAT " + _context.ToUpper() + " IS THE CONTEXT!");
}
}
class Program
{
public static void Main(string[] args)
{
var awsm1 = ServiceManager.Get<AwesomeService>("awesome");
awsm1.ShoutThineContext();
var awsm2 = ServiceManager.Get<AwesomeService>("super awesome");
awsm2.ShoutThineContext();
Console.WriteLine(awsm1.Equals(awsm2));
Console.ReadKey(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment