Skip to content

Instantly share code, notes, and snippets.

View NMZivkovic's full-sized avatar

Nikola Živković NMZivkovic

View GitHub Profile
namespace SingletonExamples
{
/// <summary>
/// Broken, non thread-save solution.
/// Don't use this code.
/// </summary>
public class SingletonFirst
{
private static SingletonFirst _instance;
namespace SingletonExamples
{
/// <summary>
/// Simple Thread safe solution.
/// </summary>
public class SingletonThreadSafe
{
private static SingletonThreadSafe _instance;
private static readonly object _lock = new object();
namespace SingletonExamples
{
/// <summary>
/// Using static constructor.
/// </summary>
public class SingletonStatic
{
private static SingletonStatic instance;
private SingletonStatic() { }
using System;
namespace SingletonExamples
{
/// <summary>
/// Solution using Lazy implementation.
/// </summary>
public class SingletonLazy
{
private static readonly Lazy<SingletonLazy> instance =
string data = "Item1";
var action1 = new Action(() => { Console.Write("This is one!"); });
var action2 = new Action(() => { Console.Write("This is two!"); });
var action3 = new Action(() => { Console.Write("This is three!"); });
switch (data)
{
case "Item1":
action1();
public class Entity
{
public string Type { get; set; }
public int GetNewValueBasedOnType(int newValue)
{
int returnValue;
switch (Type)
{
case "Type0":
var entity = new Entity() { Type = "Type1" };
var value = entity.GetNewValueBasedOnType(6);
public enum EntityType
{
Type0 = 0,
Type1 = 1,
Type2 = 2
}
public abstract class Entity
{
public abstract int GetNewValue(int newValue);
public class EntityFactory
{
private Dictionary<EntityType, Func<entity>> _entityTypeMapper;
public EntityFactory()
{
_entityTypeMapper = new Dictionary<entitytype, func<entity="">>();
_entityTypeMapper.Add(EntityType.Type0, () => { return new Type0Entity(); });
_entityTypeMapper.Add(EntityType.Type1, () => { return new Type1Entity(); });
_entityTypeMapper.Add(EntityType.Type2, () => { return new Type2Entity(); });
public class Type0Entity : Entity
{
public override int GetNewValue(int newValue)
{
return newValue;
}
}
public class Type1Entity : Entity
{