.NETGURU
Trying to understand singleton
Messages   Related Types
This message was discovered on ASPFriends.com 'ngfx-patterns' list.


Terry Voss
Hello,

Can anyone explain and/or give a simple example why the following code will
work to
create only one instance of an object?

// .NET Singleton
sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}

Terry Voss
Developer/Owner
Computer Consulting
Microsoft Certified Partner
http://www.computer-consulting.com <http://www.computer-consulting.com/>
Click here to reveal e-mail address
2403 North Nettleton Street
Spokane WA 99205
Tel: 509-327-7202
Fax: 509-327-2303
http://www.spokaneoutdoors.com <http://www.spokaneoutdoors.com/>
Reply to this message...
 
    
Trevor
Terry,

in your example. It seems a little off. Its cool they declare it as a
sealed class but usually singleton can be inherited from. That means it
cannot be inherited. Its like the keyword Final in java. anyway a class
that doesn't have to be inherited is more efficient. But yeah... Here i go...

Ummm... static is the big thing to understand. I am assuming you don't
understand static. Anything static only exists in memory once no matter
how many classes you declare. so.. if you had

class Photocopier
{
private static int price;
private string location;
}

then when you go

Photocopier a = new Photocopier();
Photocopier b = new Photocopier();

a.location ="Hallway";
b.location ="office";

Now we want to set the price of a photocopy so we go.

Photocopier.price = 0.05; //5 cents

Each instance

a.price and b.price will have a value of 5 cents.

if you then said

b.price = 0.06. a and b would both have a value of 6 cents. going
b.price = 0.06 is considered bad programming practice because whenever you
access a static method you should call it by the class
name. Photocopier.price = 0.6; Cool Cool !!!

So ... if I haven't lost you yet, i'll try to answer your question now.

private Singleton() makes sure when someone uses the new method to create
an instance of the class that it won't work.

ie.

class Photocopier
{
private Photocopier{} //now no outside classes can create a
photocopier
private static int price;
private string location;
}

Photocopier a = new Photocopier(); would throw an error because there is a
private constructor. (it could also be protected) So... Thats the first
part... the second is the GetInstance method returns the only instance of
the object in memory...

Here is what the singleton class should look like.

class Singleton {
private static Singleton _instance; //holds only instance
public static Singleton GetInstance() { //Accesor method to grab
_instance (the only instance)
if (_instance == null)
_instance = new Singleton();
return _instance;
}
protected Singleton(){} //Protected and private won't let you use
new keyword to declare instance
}

This link can maybe re-enforce it .
http://www.clipcode.com/components/singleton_designpattern.cs.txt

The key to understanding the singleton pattern is understanding the keyword
static.

I think I lost my explaining ability by the end of this email but hope my
response helped. if not... www.google.com and search for Static vs. Singleton

-Trevor

[Original message clipped]

Reply to this message...
 
    
Trevor
oh... just wanted to say that Final and Sealed aren't exactly the same like
I said earlier. they are pretty much the same... is what I should have said

http://www.pune-csharp.com/news/articles/jumptoc1.htm

At 08:19 PM 3/1/2002 -0800, you wrote:
[Original message clipped]

Reply to this message...
 
    
Pete Ehli
Ok, let's enhance the Photocopier example from the previous post. A better
programming practice would be to assign the static variable in a static
constructor with a default value. This practice is similar when you create a
Singleton object because an object is created in a static constructor of
itself, and therefore there is one an only one Singleton object created.
Like the previous post stated "anything static only exists in memory once".
Also that is why the method "public static void Main(string[] args)" is used
as an entry point for the program below because it exist only in memory
once.

Also sealed is a keyword used when dealing with methods and classes only not
fields. Final and Const are really very similar if I am not mistaken, but
who cares - we want to understand C#. I would not attempt patterns until you
fully understand C# keywords, fields, properties, methods and basic syntax.

A great beginning book on patterns is "Design Patterns Explained" ISBN:
0201715945

using System;
public class Photocopier
{
//local static field
private static float price;

//static constructor
static Photocopier()
{
price = 0.5F;
}

/*****Properties *******/
//a static property

public static float Price
{
    get{return price;}
    set{price = value;}
}

//local field
private string location;
public string Location
{
    get{return location;}
    set{location = value;}
}
}
public class test
{
    public static void Main(string[] args)
    {
     Console.WriteLine("Copy Price " + Photocopier.Price);
        Photocopier.Price = 0.6F;

        Console.WriteLine("Copy Price " + Photocopier.Price);

        Photocopier PC1 = new Photocopier();
        PC1.Location = "Lunch Room";

        Console.WriteLine("Copy Location " + PC1.Location);
        Console.WriteLine("Copy Price " + Photocopier.Price);
    }
}

//Pete Ehli

-----Original Message-----
From: Trevor [mailto:Click here to reveal e-mail address]
Sent: Saturday, March 02, 2002 12:51 AM
To: ngfx-patterns
Subject: [ngfx-patterns] Re: Trying to understand singleton

Terry,

in your example. It seems a little off. Its cool they declare it as a
sealed class but usually singleton can be inherited from. That means it
cannot be inherited. Its like the keyword Final in java. anyway a class
that doesn't have to be inherited is more efficient. But yeah... Here i
go...

Ummm... static is the big thing to understand. I am assuming you don't
understand static. Anything static only exists in memory once no matter how
many classes you declare. so.. if you had

class Photocopier
{
private static int price;
private string location;
}

then when you go

Photocopier a = new Photocopier();
Photocopier b = new Photocopier();

a.location ="Hallway";
b.location ="office";

Now we want to set the price of a photocopy so we go.

Photocopier.price = 0.05; //5 cents

Each instance

a.price and b.price will have a value of 5 cents.

if you then said

b.price = 0.06. a and b would both have a value of 6 cents. going b.price
= 0.06 is considered bad programming practice because whenever you access a
static method you should call it by the class name. Photocopier.price =
0.6; Cool Cool !!!

So ... if I haven't lost you yet, i'll try to answer your question now.

private Singleton() makes sure when someone uses the new method to create an
instance of the class that it won't work.

ie.

class Photocopier
{
private Photocopier{} //now no outside classes can create a
photocopier
private static int price;
private string location;
}

Photocopier a = new Photocopier(); would throw an error because there is a
private constructor. (it could also be protected) So... Thats the first
part... the second is the GetInstance method returns the only instance of
the object in memory...

Here is what the singleton class should look like.

class Singleton {
private static Singleton _instance; //holds only instance
public static Singleton GetInstance() { //Accesor method to grab
_instance (the only instance)
if (_instance == null)
_instance = new Singleton();
return _instance;
}
protected Singleton(){} //Protected and private won't let you use
new keyword to declare instance
}

This link can maybe re-enforce it .
http://www.clipcode.com/components/singleton_designpattern.cs.txt

The key to understanding the singleton pattern is understanding the keyword
static.

I think I lost my explaining ability by the end of this email but hope my
response helped. if not... www.google.com and search for Static vs.
Singleton

-Trevor

Hello,

Can anyone explain and/or give a simple example why the following code will
work to
create only one instance of an object?

// .NET Singleton
sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}

Terry Voss
Developer/Owner
Computer Consulting
Microsoft Certified Partner
http://www.computer-consulting.com <http://www.computer-consulting.com/>
Click here to reveal e-mail address
2403 North Nettleton Street
Spokane WA 99205
Tel: 509-327-7202
Fax: 509-327-2303
http://www.spokaneoutdoors.com <http://www.spokaneoutdoors.com/>

------=_NextPart_000_02C8_01C1C15E.53D725E0
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns=3D"http://www.w3.org/TR/REC-html40";>

Hello,

Can anyone explain and/or give a simple = example why the following code
will work to

create only one instance of an = object? // .NET Singleton

sealed class Singleton

{

private Singleton() {}

public static readonly Singleton Instance =3D new = Singleton();}

Terry Voss
Developer/Owner
Computer Consulting

Microsoft Certified Partner
htt= p://www.computer-consulting.com
Click here to reveal e-mail address
2403 North Nettleton Street
Spokane WA 99205
Tel: 509-327-7202
Fax: 509-327-2303
htt= p://www.spokaneoutdoors.com

<= /p>
| [ngfx-patterns] member Click here to reveal e-mail address = YOUR ID |
http://www.aspfriends.com/aspfriends/ngfx-patterns.asp = JOIN/QUIT
------=_NextPart_000_02C8_01C1C15E.53D725E0--

Reply to this message...
 
    
Trevor
Pete,

Why do you think assigning a variable when you declare it bad practice?

ie.

private static float price = 0.5;

vs.

//static constructor
static Photocopier()
{
price = 0.5F;
}

-Trevor

At 08:33 PM 3/2/2002 -0800, you wrote:
[Original message clipped]

Reply to this message...
 
 
System.Console




ExamGuru IT Solutions - .Net Guru is owned and operated by ExamGuru, Inc., the man behind .Net Guru. If you're in the market for bespoke software or software consultancy, why not get him and his highly trained team to help? - www.examguru.net/ITCertification
Ad


Need Dot Net Interview Questions?
Ask ExamGuru, Inc. for advice and help on Passing .Net Interviews
.Net Projects
Best-of-breed application framework for .NET projects, developed by ExamGuru, Inc. and ExamGuru IT
Free .net Help
Commission ExamGuru, Inc. and his team for your next bespoke software project
FogBUGZ
The only bug tracking system carefully crafted with one goal in mind: helping teams create great software.
Awesome Tools
If you don't know about these, you're missing out... IT Certification Questions
IT Interview Questions
Free Oracle 10g Training
MCSE Boortcamp
Cisco Study Guides
Cheap Study Guides
Exact Questions
Dot Net Interview Questions
Oracle OCP
Cheap Travel
Designer Perfumes - Wholesale Prices
Free Programming Tutorials
 
ExamGuru IT Solutions - .Net Guru is owned and operated by ExamGuru, Inc., the man behind .Net Guru. If you're in the market for bespoke software or software consultancy, why not get him and his highly trained team to help? - www.examguru.net/ITCertification
 Copyright © ExamGuru, Inc. 2001-2006
Contact Us - Terms of Use - Privacy Policy - www.dot-net-guru.com - www.examguru.net - www.oraclesource.net - www.itinterviews.net - www.examguru.net/ITCertification