Lesson 6
Now, we’ll review a simple and rather popular software development pattern Singleton and Serialization.
Agenda
Singleton
Wikipedia: “In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.”. You should use Singleton when you need only one object to be created.
Here is an example on how to create a Singleton class.
It can be also implemented using C# 6.0 auto-property feature.
Serialization
Let’s imagine you want to implement a functionality to manage some cell phone or tablet settings. It’s OK to have just one Settings object for a whole application and access it globally. Sounds as if Singleton is the way to go! For sure, Settings object should has a functionality to save and restore its state. Now, on the one hand we are going to implement a Singleton class and name it Settings and on the other hand - provide its state saving. Object’s state can be saved using Serialization. Serialization is the process of translating data structures or object state into a format that can be stored somehow. E.g. some object can be converted into array of bytes and saved into file, datbase, or transmitted via HTTP or network.
There are followings major serialization types:
- Binary serialization - converts data object into set of bytes.
- XML serialization - converts data object into XML string.
- JSON serialization - converts data object into JSON string.
Bytes, XML or JSON strings can be saved as you wish.
Well, you have some object saved (serialized), and you want to restore saved data into real C# object. This process called deserialization.
Let’s start coding Setting singleton class. Full demo can be found below. Please copy it and debug it by yourself.
This singleton class can be used as following demo shows:
References
- singleton
- Singleton implementation
- Serialization
- Binary Serialization
- XML Serialization
- JSON Serialization