Blog Archives
Singleton Pattern
I did never really care about programming patterns. I had to come up with ideas when I needed them. And back in the Commodore 64 ages, when I wrote my first “Hello World” program in Basic, there was no book about patterns anyway.
When you only allow one object instance, that is called Singleton.
Have you ever come across Remoting? You send a request to a server. There is a choice between Singleton and SingleCall. It basically means that you:
- Always use the same object or
- create a new object for each request.
Let’s say you order 4 pints of beer using your tablet PC rather than calling the sexy, blond, and 18-year-old waitress. You obviously want 4 pints at once. Therefore the correct choice would be SingleCall; 4 distinct objects. The geeky waitress reacts. She responds via her high-tech cash register: “Who are you?”. She could ask that 10 times and unless you get upset, you would always give the same answer. Any good programmer realizes that this would only require one object instance – a Singleton.
There are several ways to do this. The conceptual idea is pretty easy. (Wikipedia has some more details.) In this post I am only giving you my favourite pattern, which should always work. You don’t need more unless you want to show off with some cheap stuff.
Example:
Remove the sealed keyword in case you need to make the class inheritable.
Notice the double-check if (_Instance == null) ...
The reason is:
- The first check avoids entering the lock in 99.9999% of the calls. You save precious processor time.
- The second check avoids an unlikely multithreading problem. A thread A could enter the lock and not finish before a thread B arrives. B has to wait in front of the lock. A exits the lock, now B enters the lock. Without the second check, B would now create a new instance. And this is, what we are trying to avoid.
using System; namespace Singleton { public sealed class JustOne { private static readonly object _Lock = new object(); private static JustOne _Instance = null; private JustOne() { } public static JustOne Instance { get { if (_Instance == null) { lock (_Lock) { if (_Instance == null) _Instance = new JustOne(); } } return _Instance; } } // public new string GetHashCode() { return base.GetHashCode().ToString(); } } // class class Program { static void Main(string[] args) { JustOne A = JustOne.Instance; JustOne B = JustOne.Instance; Console.WriteLine("HashCode of object A: " + A.GetHashCode()); Console.WriteLine("HashCode of object B: " + B.GetHashCode()); Console.ReadLine(); } // main } // class } // namespace
Facade Pattern
Don’t shoot the messenger!
This is something that you are doing all the time. We just name it now. The Facade Pattern is a structural programming design pattern. To explain it in a nutshell:
A class contains many references to objects, which are invisible to the client. The client has a reduced command set to keep things simple.
The class receives the simple command and takes care about the real complexity behind the facade, which is presented to the client. Think of a cash dispenser. All you have to know is a few buttons. The legal structure, the buildings, the accounting, the risk etc. … all is invisible to the client, who only cares about getting cash at this very moment.
namespace FacadePattern { internal class Burger { public void Prepare() { } public void WarmUp() { } public void Wrap() { } } // class internal class Fries { public void Fry() { } public void KeepWarm() { } } // class internal class Drink { public enum eDrink { Coke, SevenUp, Orange, Apple, Milk, Tea, Coffee } public bool IsSugarFree { set; get; } public bool IsHot { set; get; } public void Fill(eDrink xDrink) { } } // class internal class Extras { public void AddSalt() { } public void AddKetchup() { } public void AddMayo() { } public void AddNapkin() { } } // class public class MealFacade { private Burger _Burger = new Burger(); private Fries _Fries = new Fries(); private Drink _Drink = new Drink(); private Extras _Extras = new Extras(); public void MakeClientHappy() { _Drink.IsHot = false; _Drink.IsSugarFree = true; _Drink.Fill(Drink.eDrink.Coke); _Fries.Fry(); _Burger.Prepare(); _Burger.Wrap(); _Extras.AddKetchup(); _Extras.AddSalt(); _Extras.AddNapkin(); } // } // class class Program { static void Main(string[] args) { MealFacade lBurgerMeal = new MealFacade(); lBurgerMeal.MakeClientHappy(); } // main } // class } // namespace
Prototype Pattern
Sometimes the creation of new objects is time and resource intensive. You could create a thousand objects during the program initialization and park them on a queue. The object would then be ready when needed. And looking at the Garbage Collection process in more detail, you may notice that the Generation has probably changed by then. Your object requires less processor time the older it becomes.
But this is not the topic today. It just has a similar idea. We are talking about time and/or resource intensive object creation.
The Prototype Pattern is used for cloning objects. Cloning can be substantially faster than initializing objects from scratch. Let’s say object A did load a lot of data from a file. You don’t have to do the same for object B. Simply copy object A and amend some fields.
Here is the pattern:
public interface IChocolateBar { IChocolateBar Clone(); } // interface public class MintChocolateBar : IChocolateBar { public readonly int ObjectNumber; public MintChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; } public IChocolateBar Clone() { return MemberwiseClone() as MintChocolateBar; } } // class public class DarkChocolateBar : IChocolateBar { public readonly int ObjectNumber; public DarkChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; } public IChocolateBar Clone() { return MemberwiseClone() as DarkChocolateBar; } } // class public class CloneFactory { public IChocolateBar get(IChocolateBar xChocolateBar) { return xChocolateBar.Clone(); } } // class
The pattern is not really satisfying. Is there something better? C# offers the ICloneable interface.
public class Shortcut : ICloneable { public readonly int ObjectNumber; public Shortcut(int xObjectNumber) { ObjectNumber = xObjectNumber; } public object Clone() { return MemberwiseClone(); } } // class
The problem with this interface is the missing generic type. In fact the use is obsolete and Microsoft does not recommend it anymore. We therefore build our own implementation.
public class Shortcut2 { public readonly int ObjectNumber; public Shortcut2(int xObjectNumber) { ObjectNumber = xObjectNumber; } public Shortcut2 ShallowCopy() { return MemberwiseClone() as Shortcut2; } } // class
Using an interface like
interface IShallowCopy<T> { T IShallowCopy(); } // interface public class Shortcut3<T> : IShallowCopy<T> { public readonly int ObjectNumber; public Shortcut3(int xObjectNumber) { ObjectNumber = xObjectNumber; } public T ShallowCopy() { return MemberwiseClone() as T; } } // class
is nonsense. You cannot compile and instantiate this.
What else could we do? A static clone method quickly leads us back to a factory similar type. Hence we end up with something that we were having at the very beginning today. Just keep your solutions generic and you should be fine with this pattern.
MemberwiseClone()
We were using MemberwiseClone() to keep the example source code simple. The following is important to know:
MemberwiseClone() is a shallow copy. If a field of the copied object is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.
To avoid the same references in the clone, you have to write your own Deep Copy or Lazy Copy. Your clone method must clone the object and objects inside the object.
A practical example:
Stock exchange orders need to be sent with a minimal delay. The fight for nanoseconds is tremendous. Companies even shorten the physical server cables to the exchanges in order to increase speed. One foot in length equals roughly one nanosecond these days.
The object creation for orders takes too long in the proprietary business. It is meaningful to generate orders before any decision is made. The next order sits in a queue of clones. When the machine decides to trade, then the order is taken from that queue and a few fields are populated/overridden. These are eg. trade size and price. There is no memory allocation at this late stage. As said, each nanosecond counts.
Full source code
Notice that
Console.WriteLine("ObjectNumber = " + lMintClone.ObjectNumber);
prints the same number as the original object. There are two objects at two locations in the RAM. Therefore the HashCode is different. Still the field content is the same.
using System; namespace PrototypePattern { public interface IChocolateBar { IChocolateBar Clone(); } // interface public class MintChocolateBar : IChocolateBar { public readonly int ObjectNumber; public MintChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; } public IChocolateBar Clone() { return MemberwiseClone() as MintChocolateBar; } } // class public class DarkChocolateBar : IChocolateBar { public readonly int ObjectNumber; public DarkChocolateBar(int xObjectNumber) { ObjectNumber = xObjectNumber; } public IChocolateBar Clone() { return MemberwiseClone() as DarkChocolateBar; } } // class public class CloneFactory { public IChocolateBar get(IChocolateBar xChocolateBar) { return xChocolateBar.Clone(); } } // class // IClonable is non-generic public class Shortcut : ICloneable { public readonly int ObjectNumber; public Shortcut(int xObjectNumber) { ObjectNumber = xObjectNumber; } public object Clone() { return MemberwiseClone(); } } // class public class Shortcut2 { public readonly int ObjectNumber; public Shortcut2(int xObjectNumber) { ObjectNumber = xObjectNumber; } public Shortcut2 ShallowCopy() { return MemberwiseClone() as Shortcut2; } } // class class Program { static void Main(string[] args) { CloneFactory lCloneFactory = new CloneFactory(); MintChocolateBar lMint = new MintChocolateBar(1); MintChocolateBar lMintClone = lCloneFactory.get(lMint) as MintChocolateBar; Console.WriteLine("Original object: "); Console.WriteLine("HashCode = " + lMint.GetHashCode()); Console.WriteLine("ObjectNumber = " + lMint.ObjectNumber); Console.WriteLine(); Console.WriteLine("Clone: "); Console.WriteLine("HashCode = " + lMintClone.GetHashCode()); Console.WriteLine("ObjectNumber = " + lMintClone.ObjectNumber); // !!! Console.WriteLine(); Console.WriteLine("Are the objects the same? " + (lMint == lMintClone)); DarkChocolateBar lDark = new DarkChocolateBar(2); DarkChocolateBar lDarkClone = lCloneFactory.get(lDark) as DarkChocolateBar; Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Dark chocolate: "); Console.WriteLine("Are the objects the same? " + (lMint == lMintClone)); // old school Shortcut lShort = new Shortcut(3); Shortcut lShortClone = lShort.Clone() as Shortcut; Console.WriteLine(); Console.WriteLine("ICloneable: "); Console.WriteLine("Are the objects the same? " + (lShort == lShortClone)); Console.ReadLine(); } // } // class } // namespace
example output:
Original object:
HashCode = 62125865
ObjectNumber = 1Clone:
HashCode = 44200505
ObjectNumber = 1Are the objects the same? False
Dark chocolate:
Are the objects the same? FalseICloneable:
Are the objects the same? False
Inversion of Control and Dependency Injection (advanced, Part 1), Programming Patterns
I finally had some time and spent some hours on Inversion of Control (IoC) and Dependency Injection (DI). When I did the same a few weeks ago I did not understand a lot. I got lost on the concept of inversion. I tried to figure out, what the inversion was. This blocked all and I ended up pretty much blank despite nearly an hour of pumping information into my head. When you get lost then you should do it at least properly and at full steam 😉 Well, I finally understood the headline … and the world started making sense again.
Why the name “Inversion of Control”? (IoC)
An entirely hardcoded class controls the program execution path. All branches are predetermined. By using interfaces you can decouple theses flows, so that at the time of creation the class does not exactly know what instructions to call next.
Let’s say you are using events. The class, which is raising an event, hands the control over to another class. The subscribing class is in control of the program flow, not the class that raises the event. The subscribing class can subscribe or unsubscribe. The class, which is providing the event, should not have any active control over subscriptions. Hence it is an inversion of control.
By using IoC classes become more encapsulated. Let’s say a perfect class is blind and urgently needs a guide dog. The control can now be taken over by external factors. This inverts the control entirely.
Unit testing uses that mechanism. A container can be used to control classes and change the bindings.
What is a container?
The expression “container” is rarely used in C#. The C++ world calls containers what C# calls collections. We have come across containers in my C++ posts. Follow the link for a quick refresher.
To simplify the matter we can call a UnityContainer a dictionary of objects with some additional methods.
This container performs binding between components. For instance it replaces all specific interface declarations by fully instantiated classes without the need to explicitly call any initialization.
What is dependency?
The structure of a program is: Input, Calculations, Output. The same generally applies to classes. Let’s say you want to run an analysis of a text file. That analysis class can only function properly if the required text file does exist. The calculations depend on the input. The same applies to the output, which can only run if the calculation was successful.
The input class calls the calculation class, which in turn calls the output class. As we are discussing inversion, let’s decouple the classes and implement events. In this case the output class subscribes to the calculation result event and the calculator subscribes to the input event.
What Dependency Injection? (DI)
“Dependency Injection” is a subset of “Inversion of Control”. IoC is a principle, whereas DI is an actual implementation of the principle.
DI is a software design pattern that allows removing hard-coded dependencies. First of all you do not create objects directly; you just describe how they look like. To accomplish this, the pattern uses interfaces or base classes. As the dependency is not hardcoded, the actual object can vary each time. It just needs to fulfill the inheritable pattern of an interface or base class.
public class Car { } // base class public class Audi : Car { } public class BMW : Car { } public class Exhibition { Car StageObject { set; get; } // assign Audi or BMW as the dependency object of class Exhibition }
Interfaces
What are the benefits of interfaces besides multiple inheritance? Several people can work on different problems simultaneously by using interfaces. One person for instance writes the code for logging to text files and another person writes the code for logging to databases. If both use the same interface definition, then the underlying classes can be easily replaced by each other. Interfaces are like promises to provide predefined class patterns at runtime.
Thus we end up with component separation, which is very useful in unit testing. Interfaces can eliminate unfathomable dependencies if used wisely.
Dependency Injection and Unit Testing
When you run unit tests, then you will need input data. But it could be too complex to run the entire program just to test some methods. You would try to only instantiate the minimum requirements. Think of a syringe and inject the data into the test case to create an acceptable environment. This can be difficult in case the program was not structured well. You need to examine the code to find dependencies.
I will cover some IoC/DI basics today and will follow-up on this after some other posts, which were queuing up in the last weeks:
- Calling Java from C#
- Calling C# from Java
- Implement all Java source code examples of the 15 day series C# to C++
- WPF Datagrid formatting
- Google Authenticator
- create a post index for my blog
Dependency Injection
There are several ways to implement dependencies in a class. The easiest way is to have a field that holds a reference to the dependency, which is probably the worst approach you can have in terms of flexibility.
public class Report1 { private IDataBase _DB = new DataBase(); } Report1 r1 = new Report1(); // dependency DataBase must be figured out by examining the code
You can use methods or properties to tell your classes what dependency objects they should use. The best approach though is via constructors. You can hardly miss parameters when trying to call the constructor. Of course bad constructor overloading can jeopardize this concept.
public class Car { } // base class (instead of an interface) public class Audi : Car { } public class BMW : Car { } public class Exhibition { Car StageObject { set; get; } // assign Audi or BMW as the dependency object of class Exhibition } public class Report2 { public IDataBase DB { get; private set; } public void SetDB(IDataBase xDB) { DB = xDB; } } public class Report3 { public IDataBase DB { get; set; } } public class Report4 { private IDataBase _DB; public Report4(IDataBase xDB) { _DB = xDB; } } DataBase lDB = new DataBase(); Report2 r2 = new Report2(); r2.SetDB(lDB); Report3 r3 = new Report3(); r3.DB = lDB; Report4 r4 = new Report4(lDB);
If the world was just like class Report4, then we could more or less end the post here. Unfortunately dependencies are often not that obvious. They are well hidden and you need to read the code thoroughly to build unit tests.
Dependency Injection goes further and the real take off takes place with Moq, which I will explain in the follow-up post.
The following code example was didactically compiled. You don’t need any further information, it should be self-explanatory. You can download unity by following this link or using NuGet.
using System; using Microsoft.Practices.Unity; public interface IDataBase { void QuerySomething(); } // interface public interface ITextFile { void LoadSomething(); } // interface public interface INetwork { string Text { set; get; } void ReceiveSomething(); } // interface public class Network : INetwork { public void ReceiveSomething() { Console.WriteLine("Receiving TCP data ..."); } public string Text { set; get; } } // class public class DataBase : IDataBase { private string _Dummy = "I am doing something."; public void QuerySomething() { Console.WriteLine(_Dummy); } } // class public class TextFile1 : ITextFile { public void LoadSomething() { Console.WriteLine("TF1: Loading something..."); } } // class public class TextFile2 : ITextFile { public void LoadSomething() { Console.WriteLine("TF2: Loading something..."); } } // class public class TextFile3 : ITextFile { public void LoadSomething() { Console.WriteLine("TF3: Loading something..."); } } // class public class Report5 { public string Text = "#N/A"; private IDataBase _DB; public readonly ITextFile TF; public IDataBase getDB() { return _DB; } public Report5(IDataBase xDB, ITextFile xTextFile) { _DB = xDB; TF = xTextFile; } } // class public class Report6 { public readonly string Text1; public readonly string Text2; private readonly ITextFile _TextFile; public readonly INetwork Network; public Report6(ITextFile xTextFile, INetwork xNetwork, string xText1, string xText2) { _TextFile = xTextFile; Network = xNetwork; Text1 = xText1; Text2 = xText2; } // constructor } // class class Program { static void Main(string[] args) { UnityContainer lContainer = new UnityContainer(); // using Microsoft.Practices.Unity; Report5 r; // insufficient data Console.WriteLine("test: insufficient data"); Console.WriteLine("Registering IDataBase"); lContainer.RegisterType(typeof(IDataBase), typeof(DataBase)); // whenever someone asks for an IDataBase, then return a new DataBase instance try { r = lContainer.Resolve<Report5>(); // throws an exception, because ITextFile is undefined } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine(); // full data Console.WriteLine("test: sufficient data"); Console.WriteLine("Registering ITextFile TF1"); Console.WriteLine("IDataBase is still registered"); lContainer.RegisterType(typeof(ITextFile), typeof(TextFile1)); r = lContainer.Resolve<Report5>(); Console.WriteLine("type of r.TF is " + r.TF.GetType()); // TextFile1 r.getDB().QuerySomething(); r.TF.LoadSomething(); // this is TextFile1 Console.WriteLine(); // override a previous type registration with another type Console.WriteLine("test: override a previous type registration with another type"); Console.WriteLine("Registering ITextFile TF2"); lContainer.RegisterType(typeof(ITextFile), typeof(TextFile2)); // override the first type registration //lContainer.RegisterType<ITextFile, TextFile2>(); // same as lContainer.RegisterType(typeof(ITextFile), typeof(TextFile2)); r = lContainer.Resolve<Report5>(); Console.WriteLine("type of r.TF is " + r.TF.GetType()); // TextFile2 r.getDB().QuerySomething(); r.TF.LoadSomething(); // this is TextFile2 Console.WriteLine(); // override a previous type registration with an instance Console.WriteLine("test: override a previous type registration with an instance"); Console.WriteLine("Registering an instance of TextFile3"); ITextFile lTextFile = new TextFile3(); lContainer.RegisterInstance(lTextFile); r = lContainer.Resolve<Report5>(); Console.WriteLine("type of r.TF is " + r.TF.GetType()); // TextFile3 r.getDB().QuerySomething(); r.TF.LoadSomething(); // this is TextFile3 Console.WriteLine(); // using names to register instances Console.WriteLine("test: using names to register instances"); lContainer.RegisterType<Report5, Report5>(); // creates a default class without any name Report5 a = new Report5(r.getDB(), r.TF); lContainer.RegisterInstance("A", a); a.Text = "Report A"; Report5 b = new Report5(r.getDB(), r.TF); lContainer.RegisterInstance("B", b); b.Text = "Report B"; r = lContainer.Resolve<Report5>("A"); Console.WriteLine("got " + r.Text); r = lContainer.Resolve<Report5>("B"); Console.WriteLine("got " + r.Text); r = lContainer.Resolve<Report5>(); Console.WriteLine("got " + r.Text); r.Text = "same instance?"; r = lContainer.Resolve<Report5>("X"); Console.WriteLine("got " + r.Text); // new instance r = lContainer.Resolve<Report5>(); Console.WriteLine("got " + r.Text); // new instance Console.WriteLine(); // => HAVE A LOOK AT THE BELOW CONTAINER SNAPSHOT => there are 3 instances for Report5 // using names to register instances Console.WriteLine("test: revision, using the same instance"); Console.WriteLine("ContainerControlledLifetimeManager: re-use instances (singleton behaviour for objects)"); lContainer.RegisterType<Report5, Report5>(new ContainerControlledLifetimeManager()); r = lContainer.Resolve<Report5>(); Console.WriteLine("got " + r.Text); r.Text = "same instance?"; r = lContainer.Resolve<Report5>("X"); Console.WriteLine("got " + r.Text); // new instance r = lContainer.Resolve<Report5>(); Console.WriteLine("got " + r.Text); // same instance !!!!! Console.WriteLine(); // constructors with parameters lContainer.RegisterType<INetwork, Network>(); lContainer.RegisterType<ITextFile, TextFile2>(); Console.WriteLine("test: constructors with parameters"); ResolverOverride[] lParameters = new ResolverOverride[] { new ParameterOverride("xText1", "Hello "), new ParameterOverride("xText2", "world") }; Report6 lReport6 = lContainer.Resolve<Report6>(lParameters); Console.WriteLine("Report6 text field values are: " + lReport6.Text1 + lReport6.Text2); Console.ReadLine(); } // } // class
example output:
test: insufficient data
Registering IDataBase
Resolution of the dependency failed, type = “Report5”, name = “(none)”.
Exception occurred while: while resolving.
Exception is: InvalidOperationException – The type ITextFile does not have an ac
cessible constructor.
———————————————–
At the time of the exception, the container was:
Resolving Report5,(none)
Resolving parameter “xTextFile” of constructor Report5(IDataBase xDB, ITextFil
e xTextFile)
Resolving ITextFile,(none)
test: sufficient data
Registering ITextFile TF1
IDataBase is still registered
type of r.TF is TextFile1
I am doing something.
TF1: Loading something…
test: override a previous type registration with another type
Registering ITextFile TF2
type of r.TF is TextFile2
I am doing something.
TF2: Loading something…
test: override a previous type registration with an instance
Registering an instance of TextFile3
type of r.TF is TextFile3
I am doing something.
TF3: Loading something…
test: using names to register instances
got Report A
got Report B
got #N/A
got #N/A
got #N/A
test: revision, using the same instance
ContainerControlledLifetimeManager: re-use instances (singleton behaviour for ob
jects)
got #N/A
got #N/A
got same instance?
test: constructors with parameters
Report6 text field values are: Hello world