<p><code style="display:block;white-space:pre-wrap">
using System;
namespace SingletonPatternEx
{
public sealed class Singleton
{
private static readonly Singleton instance=new Singleton();
private int numberOfInstances = 0;
//Private constructor is used to prevent
//creation of instances with 'new' keyword outside this class
private Singleton()
{
Console.WriteLine("Instantiating inside the private constructor.");
numberOfInstances++;
Console.WriteLine("Number of instances ={0}", numberOfInstances);
}
public static Singleton Instance
{
get
{
Console.WriteLine("We already have an instance now.Use it.");
return instance;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***Singleton Pattern Demo***\n");
//Console.WriteLine(Singleton.MyInt);
// Private Constructor.So,we cannot use 'new' keyword.
Console.WriteLine("Trying to create instance s1.");
Singleton s1 = Singleton.Instance;
Console.WriteLine("Trying to create instance s2.");
Singleton s2 = Singleton.Instance;
if (s1 == s2)
{
Console.WriteLine("Only one instance exists.");
}
else
{
Console.WriteLine("Different instances exist.");
}
Console.Read();
}
}
}
</code></p>
Category: Design Patterns
Prototype
<p><code style="display:block;white-space:pre-wrap">
//BasicCar.cs
using System;
namespace PrototypePattern
{
public abstract class BasicCar
{
public string ModelName{get;set;}
public int Price {get; set;}
public static int SetPrice()
{
int price = 0;
Random r = new Random();
int p = r.Next(200000, 500000);
price = p;
return price;
}
public abstract BasicCar Clone();
}
}
//Nano.cs
using System;
namespace PrototypePattern
{
public class Nano:BasicCar
{
public Nano(string m)
{
ModelName = m;
}
public override BasicCar Clone()
{
return (Nano) this.MemberwiseClone();//shallow Clone
}
}
}
//Ford.cs
using System;
namespace PrototypePattern
{
public class Ford:BasicCar
{
public Ford(string m)
{
ModelName = m;
}
public override BasicCar Clone()
{
return (Ford)this.MemberwiseClone();
}
}
}
//Client
using System;
namespace PrototypePattern
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***Prototype Pattern Demo***\n");
//Base or Original Copy
BasicCar nano_base = new Nano("Green Nano") {Price = 100000};
BasicCar ford_base = new Ford("Ford Yellow") {Price = 500000};
BasicCar bc1;
//Nano
bc1 = nano_base.Clone();
bc1.Price = nano_base.Price+BasicCar.SetPrice();
Console.WriteLine("Car is: {0}, and it's price is Rs. {1} ",bc1.ModelName,bc1.Price);
//Ford
bc1 = ford_base.Clone();
bc1.Price = ford_base.Price+BasicCar.SetPrice();
Console.WriteLine("Car is: {0}, and it's price is Rs. {1}", bc1.ModelName, bc1.Price);
Console.ReadLine();
}
}
}
</code></p>