Let's start from simpliest things.
The main idea of Singletone pattern is: private class constructor, private field with the only instance of class and public method that returns this instance.
We can implement it this way (there are variations, but as I can see this is the most popular way):
To test this pattern you can use next code:
The main idea of Singletone pattern is: private class constructor, private field with the only instance of class and public method that returns this instance.
We can implement it this way (there are variations, but as I can see this is the most popular way):
class SingletoneExample { private static SingletoneExample instance = null; private SingletoneExample() { } public static SingletoneExample getInstance { public get { if (instance == null) { instance = new SingletoneExample(); } return instance; } private set; } }
To test this pattern you can use next code:
using System; namespace Singletone { class Program { static void Main(string[] args) { SingletoneExample singl = SingletoneExample.getInstance; singl.Prop = "op"; Console.WriteLine(singl.Prop); SingletoneExample singl1 = SingletoneExample.getInstance; Console.WriteLine(singl1.Prop); Console.ReadLine(); } } class SingletoneExample { private static SingletoneExample instance = null; private string prop; private SingletoneExample() { } public static SingletoneExample getInstance { public get { if (instance == null) { instance = new SingletoneExample(); } return instance; } private set; } public string Prop { public get { return prop; } public set { prop = value; } } } }
Комментариев нет:
Отправить комментарий