Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add singleton pattern #105

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Best Practices/Design Patterns/Creational Patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,38 @@ static void Main(string[] args)
}

```

#### Singleton
This pattern allows existence of only one instance of the class throughout the system.

Works well with other creational design patterns. May improve performance. Better alternative to global variables. Enables lazy initialization.

Violates Single Responsibility Principle. May cause problems with multithreading. May cause problems with Unit testing.

```c#
//singleton class
public class GameManager
{
private static GameManager gameManager;

public static GameManager GetGameManager()
{ // lazy initialization
if (gameManager == null)
{
gameManager = new GameManager();
}
return gameManager;
}

public void GetConfigs()
{
Console.WriteLine("Configs");
}
}

//Usage
static void Main(string[] args)
{
GameManager gameManager = new GameManager()
gameManager.GetConfigs();
}