Last active
June 27, 2018 07:35
-
-
Save PTwr/be475a071e28d39df06c8ed564560f3a to your computer and use it in GitHub Desktop.
Lazy singleton for service with default implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace ConsoleApp7 | |
{ | |
public interface IService | |
{ | |
string Foo(); | |
string Bar(string a); | |
} | |
//Static class is a must: "A namespace cannot directly contain members such as fields or methods" :( | |
public static class Dummy// : IService //static class can not implement interfaces :( | |
{ | |
private static IService _service = null; | |
public static IService Singleton | |
{ | |
get | |
{ | |
return _service ?? new BaseImplementation(); | |
} | |
set | |
{ | |
_service = value; | |
} | |
} | |
public static string Bar(string a) | |
{ | |
return Singleton.Bar(a); | |
} | |
public static string Foo() | |
{ | |
return Singleton.Foo(); | |
} | |
} | |
public class BaseImplementation : IService | |
{ | |
public BaseImplementation() | |
{ | |
Dummy.Singleton = this; | |
} | |
public virtual string Bar(string a) | |
{ | |
return a.ToUpper(); | |
} | |
public virtual string Foo() | |
{ | |
return this.GetType().ToString(); | |
} | |
} | |
public class MyImplementation : BaseImplementation | |
{ | |
public override string Bar(string a) | |
{ | |
return a.ToLower(); | |
} | |
public override string Foo() | |
{ | |
return this.GetType().ToString(); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(Dummy.Foo()); | |
Console.WriteLine(Dummy.Bar("AaA")); | |
new MyImplementation(); | |
Console.WriteLine(Dummy.Foo()); | |
Console.WriteLine(Dummy.Bar("AaA")); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment