Skip to content

Commit

Permalink
Refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
eminencegrs committed Nov 1, 2024
1 parent 53613bd commit 56af417
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
6 changes: 3 additions & 3 deletions Creational/DesignPatterns.Singleton/SingletonWithLazy.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
namespace DesignPatterns.Singleton;

public class SingletonWithLazy
public sealed class SingletonWithLazy
{
private static readonly Lazy<SingletonWithLazy> instance = new(() => new SingletonWithLazy());
private static readonly Lazy<SingletonWithLazy> LazyInstance = new(() => new SingletonWithLazy());

/// <summary>
/// The private constructor is declared to prevent instantiation directly, via calling a default constructor.
Expand All @@ -12,5 +12,5 @@ private SingletonWithLazy()
Console.WriteLine($"An instance of {nameof(SingletonWithLazy)} has been created.");
}

public static SingletonWithLazy Instance => instance.Value;
public static SingletonWithLazy Instance => LazyInstance.Value;
}
12 changes: 7 additions & 5 deletions Creational/DesignPatterns.Singleton/SingletonWithLock.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
namespace DesignPatterns.Singleton;
using System.Diagnostics;

public class SingletonWithLock
namespace DesignPatterns.Singleton;

public sealed class SingletonWithLock
{
private static SingletonWithLock? instance = null;
private static readonly object lockObj = new();
private static readonly object LockObject = new();

/// <summary>
/// The private constructor is declared to prevent instantiation directly, via calling a default constructor.
/// </summary>
private SingletonWithLock()
{
Console.WriteLine($"An instance of {nameof(SingletonWithLock)} has been created.");
Debug.WriteLine($"An instance of {nameof(SingletonWithLock)} has been created.");
}

public static SingletonWithLock Instance
Expand All @@ -19,7 +21,7 @@ public static SingletonWithLock Instance
{
// The cost of executing the lock operation is significantly higher
// in comparison to the straightforward pointer check `instance != null`.
lock (lockObj)
lock (LockObject)
{
return instance ??= new SingletonWithLock();
}
Expand Down

0 comments on commit 56af417

Please sign in to comment.