C
C#4mo ago
textYash

Enum based Singleton

This is the description for my job training task:
Implement the Singleton class using the Enum approach to create a thread-safe Singleton instance without the need for lazy initialization or explicit locking.

Write a program to demonstrate that the Singleton instance is created only once and accessed safely by multiple threads using the Enum approach.
Implement the Singleton class using the Enum approach to create a thread-safe Singleton instance without the need for lazy initialization or explicit locking.

Write a program to demonstrate that the Singleton instance is created only once and accessed safely by multiple threads using the Enum approach.
I don't understand how to implement this. I find myself coding the same old implementation with a static backing field. Not here to get my homework done. I'm genuinely trying to learn
8 Replies
SleepWellPupper
SleepWellPupper4mo ago
What is "the Enum approach"? Also, a solution to singleton without lazy or locking is to simply instantiate eagerly a static field/property and hide the constructor of your class.
Anton
Anton4mo ago
they probably mean constants wrapped in a class static constructors are thread safe afaik so yeah, that's probably the anwer
canton7
canton74mo ago
I assume that's referring to something earlier in the training material?
textYash
textYashOP4mo ago
That's what I don't understand... I kinda have no one to ask what's to be done oh okay its actually a thing. I found java implementations online:
public enum SingletonEnum {
INSTANCE;

int value;

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}
}
public enum SingletonEnum {
INSTANCE;

int value;

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}
}
canton7
canton74mo ago
Java enums are very different to C# enums You can't do that in C#
textYash
textYashOP4mo ago
yea exactly im unable to find any ACTUAL implementation I found this C# based on on a website:
public enum ProductEnum
{
INSTANCE
}
public static class ProductEnumExtensions
{
private static int state = 0;
public static void DoSomething(this ProductEnum it) {
System.Console.WriteLine("I did something for the {0} time", ++state);
}
}
public enum ProductEnum
{
INSTANCE
}
public static class ProductEnumExtensions
{
private static int state = 0;
public static void DoSomething(this ProductEnum it) {
System.Console.WriteLine("I did something for the {0} time", ++state);
}
}
but I don't think the enum plays any role here
canton7
canton74mo ago
Yes, someone copied some Java docs, and didn't update them for C#
SleepWellPupper
SleepWellPupper4mo ago
Well java enum singletons seem to be simple static readonly fields/props that are initialized eagerly to their value.
Want results from more Discord servers?
Add your server