i try to learn design pattern, but it's really really hard to understand main idea of OOD. i have created my software with classic method. On the other hand i want to learn OOD. why i need singleton and others? i coded some simple program: one of them clasical(my style), the other is singleton pattern.Please teach me why do i need singleton. my method better and clear than it :)
my style: (C#)
public partial class Singletonsuz : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Loadbalancer balancer = new Loadbalancer();
for (int i = 0 ; i < 15 ; i++)
{
string server = balancer.Server;
Response.Write("Dispatch Request to: " + server);
}
}
}
class Loadbalancer
{
private List<string> _servers = new List<string>();
private Random _random = new Random();
public Loadbalancer()
{
_servers.Add("ServerI");
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
_servers.Add("ServerV");
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
}
}
}
SINGLETON:
public partial class SingletonDP2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
for (int i = 0; i < 15; i++)
{
string server = balancer.Server;
Response.Write("Dispatch Request to: " + server );
}
}
class LoadBalancer
{
private static LoadBalancer _instance;
private List<string> _servers = new List<string>();
private Random _random = new Random();
private static object syncLock = new object();
protected LoadBalancer()
{
_servers.Add("ServerI");
_servers.Add("ServerII");
_servers.Add("ServerIII");
_servers.Add("ServerIV");
_servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
if (_instance == null)
{
lock (syncLock)
{
if (_instance == null)
{
_instance = new LoadBalancer();
}
}
}
return _instance;
}
public string Server
{
get
{
int r = _random.Next(_servers.Count);
return _servers[r].ToString();
}
}
}
}