RUVIDEO
Поделитесь видео 🙏

Why is singleton class sealed смотреть онлайн

Text version of the video
http://csharp-video-tutorials.blogspot.com/2017/05/why-is-singleton-class-sealed.html

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.
https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1

Slides
http://csharp-video-tutorials.blogspot.com/2017/05/why-is-singleton-class-sealed_19.html

In this tutorial we will discuss
A quick Recap of Singleton version which have discussed in the previous session and
We will focus on why we used Sealed keyword and
Why we need to seal the singleton class

In our previous video we discussed
Why we need to create a singleton class and how we can apply singleton design pattern to a class
We have changed the class to restrict external instantiation by changing the public constructor to private and then we provided a public property to access this class
We have proved that adding Private constructor will prevent us instantiating a new class
We have further sealed down this class to avoid any inheritance

You might be wondering why we need to seal the class when a private constructor is present.

Let’s first remove the sealed keyword and check that. Let’s create another class called DerivedSingleton and Inherit the singleton class. Let's compile the code and look at that it has thrown an error saying Singleton is inaccessible due to its protection level. This error is because of private constructor.

Now you might be thinking that when a private constructor is restricting the inheritance then why we need to apply sealed keyword to the class.

Let’s just move this new class inside the Singleton class. By moving this class inside the Singleton class it has now become nested or child class of the main singleton class

Singleton.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonDemo
{
public class Singleton
{
private static int counter = 0;
private static object obj = new object();

private Singleton()
{
counter++;
Console.WriteLine("Counter Value " + counter.ToString());
}
private static Singleton instance = null;

public static Singleton GetInstance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}

public void PrintDetails(string message)
{
Console.WriteLine(message);
}

public class DerivedSingleton : Singleton
{

}
}
}

What is a nested class? A class with in another class is called a nested class. At this moment we will skip any further discussions related to nested class as it is out of scope for this tutorial. However, for more details please refer to MSDN article about nested classes and types.

Now that we have moved the derived class to nested class lets compile the program and check. Look at that we are able to compile this successfully.

Now, let’s switch to main program and access the nested class.

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SingletonDemo
{
class Program
{
static void Main(string[] args)
{
Singleton fromStudent = Singleton.GetInstance;
fromStudent.PrintDetails("From Student");

Singleton fromEmployee = Singleton.GetInstance;
fromEmployee.PrintDetails("From Employee");

Console.WriteLine("-------------------------------------");

Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton();
derivedObj.PrintDetails("From Derived");

Console.ReadLine();
}
}
}

Lets run the program. Look at that the counter value has incremented to 2 proving that we are able to create multiple instances of the singleton using the nested derived class.

This violates the principle of singleton. Let’s go back to the Singleton and make the class as sealed. Let’s compile the program

Look at that we have got an error when we compile the program saying we cannot derive a sealed class. With this we have proved that private constructor helps in preventing any external instantiations of objects and sealed will prevent the class inheritances.

In the next session we will discuss how to handle thread safety in singleton as the current version can create multiple instances in multithreaded environments.

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Why is singleton class sealed» бесплатно и без регистрации, вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.