Singleton Pattern | Creational Design Pattern
public class ProductionScheduler
{
// Private static instance variable to hold the single instance of the class
private static ProductionScheduler instance;
// Private constructor to prevent creating instances directly
private ProductionScheduler()
{
// Initialization code, e.g., setting up production schedule parameters
}
// Public method to access the single instance of the class
public static ProductionScheduler Instance
{
get
{
// If the instance doesn't exist, create it
if (instance == null)
{
instance = new ProductionScheduler();
}
// Return the existing instance
return instance;
}
}
// Method to schedule production for a specific car model
public void ScheduleProduction(string carModel)
{
Console.WriteLine($"Production scheduled for {carModel}.");
}
}
class Program
{
static void Main()
{
// Accessing the singleton instance of the ProductionScheduler
ProductionScheduler scheduler = ProductionScheduler.Instance;
// Scheduling production for different car models
scheduler.ScheduleProduction("Sedan");
scheduler.ScheduleProduction("SUV");
// Another part of the application can also access the same scheduler
ProductionScheduler anotherScheduler = ProductionScheduler.Instance;
anotherScheduler.ScheduleProduction("Electric Car");
// Both instances refer to the same ProductionScheduler object
Console.WriteLine(scheduler == anotherScheduler); // Output: True
}
}
Comments
Post a Comment