Design Pattern: Singleton Programming using the Singleton Design Pattern. You mu
ID: 3743024 • Letter: D
Question
Design Pattern: Singleton
Programming using the Singleton Design Pattern.
You must provide code that uses and demonstrates the Singleton Design Pattern.
The goal of this project is to show off your understanding of the Design Pattern, NOT getting the project working without it.
Make sure your project has no errors or warnings.
Programming Guidelines:
Create a Scoring/Game information Data Structure that uses the Singleton Design Pattern.The data structure should store at least three types of information if not more:
Score,
Main character health,
Money,
and so on.
Your singleton will need to have public properties so that you can update the information.
You will need a scene in your project to show your singleton works.
The easiest way to do this is to use the UI components of Unity3D.
This project has to work in Unity3D.
Your Singleton class will NOT extend the MonoBehaviour class.
All code will be done in C#.
Programming Hints:
Look up the UI information from the Unity3d's manual section.
We can write information to the console window by using: Debug.Log
Debug.Log("Your message here.");
Explanation / Answer
public class Singleton
{
private static Singleton instance = new Singleton();
private Singleton() { }
public static Singleton GetInstance
{
get
{
return instance;
}
}
}
////lazy initialization of singleton
public class Singleton
{
private static Singleton instance = null;
private Singleton() { }
public static Singleton GetInstance
{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
////Thread-safe (Double-checked Locking) initialization of singleton
public class Singleton
{
private static Singleton instance = null;
private Singleton() { }
private static object lockThis = new object();
public static Singleton GetInstance
{
get
{
lock (lockThis)
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
}