Implementing object hierarchy in client/server development

  • Thread starter Thread starter Mark Neilson
  • Start date Start date
M

Mark Neilson

1. What is the best way to make a single instance of my top level class
(DLL) internally available to all other members of the assembly? The top
level object is where all other access is made in to the program. Where and
how do I declare and initialise this object?

For instance, it would have property implementation like this:

//*******************************************
public MyClass1 Class1
{
get
{
// always return a single instance of this class
if (this.class1 == null)
{
this.class1 = new MyClass1();
}
return this.class1;
}
}

private MyClass1 class1;
//****************************************
2. For a front end built using this server, what is the best way to gain
access in to this top level class in to the back end entry object? Where
and how do I declare an initialise this variable?
 
This sounds liek you are creating a facade class. Look at the singleton
pattern for supporting one instance, though take heed that one of the GOF
fathers said Singelton is one pattern he wish he hadnt put in the GoF book.
To gain access to the class, create a factory in the assembly. A factory in
this case is simply one level of indirection.
 
Hello Mark,

Thanks for posting in the group.

Based on my understanding, now the question is: How to declare and use a
singleton object in C#? Please correct me if I have misunderstood it.

Generally speaking, the intent of the Singleton pattern as defined in
Design Patterns is to "ensure a class has only one instance, and provide a
global point of access to it". The model for a singleton is very
straightforward. There is (usually) only one singleton instance. Clients
access the singleton instance through one well-known access point. The
client in this case is an object that needs access to a sole instance of a
singleton.

We can refer to a simple C++ singleton sample:

// Declaration
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
}

// Implementation
Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

Let's examine this code for a moment. This simple class has one member
variable and that is a pointer to itself. Notice that the constructor is
protected and that the only public method is the Instance method. In the
implementation of the Instance method, there is a control block (if) that
checks to see if the member variable has been initialized, and if not
creates a new instance. This lazy initialization in the control block means
that the Singleton instance is initialized, or created, only on the first
call to the Instance() method. For many applications, this approach works
just fine. But, for multithreaded applications, this approach proves to
have a potentially hazardous side effect. If two threads manage to enter
the control block at the same time, two instances of the member variable
could be created. To solve this, you might be tempted to merely place a
critical section around the control block in order to guarantee thread
safety. If you do this, then all calls to the Instance method would be
serialized and could have a very negative impact on performance, depending
on the application.

Microsoft .NET Framework has addressed all of these issues, thus making it
easier to implement a singleton without the adverse side effects we
discussed thus far. The following sample uses .NET, is a minimal Singleton
class based loosely on the original GoF pattern, and still gets similar
behavior.

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

The Framework internally guarantees thread safety on static type
initialization. In other words, in the example above, there is only one
instance that would ever be created of the Singleton class.

For the usage of this class, please refer to the following:

Sample Singleton Usage
sealed class SingletonCounter {
public static readonly SingletonCounter Instance =
new SingletonCounter();
private long Count = 0;
private SingletonCounter() {}
public long NextValue() {
return ++Count;
}
}

class SingletonClient {
[STAThread]
static void Main() {
for (int i=0; i<20; i++) {
Console.WriteLine("Next singleton value: {0}",
SingletonCounter.Instance.NextValue());
}
}
}

For details on this topic, please refer to MSDN article "Exploring the
Singleton Design Pattern" at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/
singletondespatt.asp.

Does that answer your question?

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Yan that is an excellent answer. I do have one question however. Based on
this part of your advice:
// .NET Singleton
sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}

How would you instantiate a singleton that requires constructor parameters,
or indeed any further information during loading?

Nick.

Yan-Hong Huang said:
Hello Mark,

Thanks for posting in the group.

Based on my understanding, now the question is: How to declare and use a
singleton object in C#? Please correct me if I have misunderstood it.

Generally speaking, the intent of the Singleton pattern as defined in
Design Patterns is to "ensure a class has only one instance, and provide a
global point of access to it". The model for a singleton is very
straightforward. There is (usually) only one singleton instance. Clients
access the singleton instance through one well-known access point. The
client in this case is an object that needs access to a sole instance of a
singleton.

We can refer to a simple C++ singleton sample:

// Declaration
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
}

// Implementation
Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

Let's examine this code for a moment. This simple class has one member
variable and that is a pointer to itself. Notice that the constructor is
protected and that the only public method is the Instance method. In the
implementation of the Instance method, there is a control block (if) that
checks to see if the member variable has been initialized, and if not
creates a new instance. This lazy initialization in the control block means
that the Singleton instance is initialized, or created, only on the first
call to the Instance() method. For many applications, this approach works
just fine. But, for multithreaded applications, this approach proves to
have a potentially hazardous side effect. If two threads manage to enter
the control block at the same time, two instances of the member variable
could be created. To solve this, you might be tempted to merely place a
critical section around the control block in order to guarantee thread
safety. If you do this, then all calls to the Instance method would be
serialized and could have a very negative impact on performance, depending
on the application.

Microsoft .NET Framework has addressed all of these issues, thus making it
easier to implement a singleton without the adverse side effects we
discussed thus far. The following sample uses .NET, is a minimal Singleton
class based loosely on the original GoF pattern, and still gets similar
behavior.

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

The Framework internally guarantees thread safety on static type
initialization. In other words, in the example above, there is only one
instance that would ever be created of the Singleton class.

For the usage of this class, please refer to the following:

Sample Singleton Usage
sealed class SingletonCounter {
public static readonly SingletonCounter Instance =
new SingletonCounter();
private long Count = 0;
private SingletonCounter() {}
public long NextValue() {
return ++Count;
}
}

class SingletonClient {
[STAThread]
static void Main() {
for (int i=0; i<20; i++) {
Console.WriteLine("Next singleton value: {0}",
SingletonCounter.Instance.NextValue());
}
}
}

For details on this topic, please refer to MSDN article "Exploring the
Singleton Design Pattern" at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/
singletondespatt.asp.

Does that answer your question?

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
There are many workarounds to this issue. However, honestly, see if you can
find a way to avoid requiring parameters during construction. Allow the
object itself to be created, and then use methods on the object to handle
further initialization. Otherwise, you end up with some very interesting
(and somewhat difficult) threading issues.

--- Nick

Nick said:
Yan that is an excellent answer. I do have one question however. Based on
this part of your advice:
// .NET Singleton
sealed class Singleton
{
private Singleton() {}
public static readonly Singleton Instance = new Singleton();
}

How would you instantiate a singleton that requires constructor parameters,
or indeed any further information during loading?

Nick.

Yan-Hong Huang said:
Hello Mark,

Thanks for posting in the group.

Based on my understanding, now the question is: How to declare and use a
singleton object in C#? Please correct me if I have misunderstood it.

Generally speaking, the intent of the Singleton pattern as defined in
Design Patterns is to "ensure a class has only one instance, and provide a
global point of access to it". The model for a singleton is very
straightforward. There is (usually) only one singleton instance. Clients
access the singleton instance through one well-known access point. The
client in this case is an object that needs access to a sole instance of a
singleton.

We can refer to a simple C++ singleton sample:

// Declaration
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
}

// Implementation
Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

Let's examine this code for a moment. This simple class has one member
variable and that is a pointer to itself. Notice that the constructor is
protected and that the only public method is the Instance method. In the
implementation of the Instance method, there is a control block (if) that
checks to see if the member variable has been initialized, and if not
creates a new instance. This lazy initialization in the control block means
that the Singleton instance is initialized, or created, only on the first
call to the Instance() method. For many applications, this approach works
just fine. But, for multithreaded applications, this approach proves to
have a potentially hazardous side effect. If two threads manage to enter
the control block at the same time, two instances of the member variable
could be created. To solve this, you might be tempted to merely place a
critical section around the control block in order to guarantee thread
safety. If you do this, then all calls to the Instance method would be
serialized and could have a very negative impact on performance, depending
on the application.

Microsoft .NET Framework has addressed all of these issues, thus making it
easier to implement a singleton without the adverse side effects we
discussed thus far. The following sample uses .NET, is a minimal Singleton
class based loosely on the original GoF pattern, and still gets similar
behavior.

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

The Framework internally guarantees thread safety on static type
initialization. In other words, in the example above, there is only one
instance that would ever be created of the Singleton class.

For the usage of this class, please refer to the following:

Sample Singleton Usage
sealed class SingletonCounter {
public static readonly SingletonCounter Instance =
new SingletonCounter();
private long Count = 0;
private SingletonCounter() {}
public long NextValue() {
return ++Count;
}
}

class SingletonClient {
[STAThread]
static void Main() {
for (int i=0; i<20; i++) {
Console.WriteLine("Next singleton value: {0}",
SingletonCounter.Instance.NextValue());
}
}
}

For details on this topic, please refer to MSDN article "Exploring the
Singleton Design Pattern" at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/
singletondespatt.asp.

Does that answer your question?

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Nick I think thats my point to be honest. This next piece of "further
initialization" would require thread safety wouldnt it? Someone would have
to call into the object to initialize it, which would require some critical
section. Maybe I'm not seeing something...

N.

Nick Malik said:
There are many workarounds to this issue. However, honestly, see if you can
find a way to avoid requiring parameters during construction. Allow the
object itself to be created, and then use methods on the object to handle
further initialization. Otherwise, you end up with some very interesting
(and somewhat difficult) threading issues.

--- Nick

Nick said:
Yan that is an excellent answer. I do have one question however. Based on
this part of your advice:


How would you instantiate a singleton that requires constructor parameters,
or indeed any further information during loading?

Nick.
provide
of
making
it
easier to implement a singleton without the adverse side effects we
discussed thus far. The following sample uses .NET, is a minimal Singleton
class based loosely on the original GoF pattern, and still gets similar
behavior.

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

The Framework internally guarantees thread safety on static type
initialization. In other words, in the example above, there is only one
instance that would ever be created of the Singleton class.

For the usage of this class, please refer to the following:

Sample Singleton Usage
sealed class SingletonCounter {
public static readonly SingletonCounter Instance =
new SingletonCounter();
private long Count = 0;
private SingletonCounter() {}
public long NextValue() {
return ++Count;
}
}

class SingletonClient {
[STAThread]
static void Main() {
for (int i=0; i<20; i++) {
Console.WriteLine("Next singleton value: {0}",
SingletonCounter.Instance.NextValue());
}
}
}

For details on this topic, please refer to MSDN article "Exploring the
Singleton Design Pattern" at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/
 
Hi Nick,

That is a good question. Nick has provided you a method.

Besides, I think you could revise the default private Singleton() {} to let
it have several default parameters. In this way, if you didn't transfer
parameters, it will use default values. If you transfer parameters, it will
use the new parameter to initialized.

Also, you could refer to Double-Check Lock in C# in that article that I
introduced. Its main code is:
class Singleton
{
public static Singleton Instance() {
if (_instance == null) {
lock (typeof(Singleton)) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
protected Singleton() {}
private static volatile Singleton _instance = null;
}

By the way, we could send post notify email to you when there is useful
replied to your post in the group. If you want to receive it, please go to
http://support.microsoft.com/default.aspx?scid=/servicedesks/msdn/nospam.asp
&SD=msdn to create a no spam alias.

Thanks again for participating the community.

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Hi Yan,

Thanks for getting back. Looking at Nick Maliks suggestion, while it would
work, the concurrency issue would arise when setting the properties. What I
liked about the original point you raised was that you avoided having to
introduce a lock. I am working in a multi-threaded environment and have
done the vanilla singleton using locks. Using the double-check lock
obviously works, but potentially introduces a bottleneck.

If the singleton requires external paramaterization (which is not uncommon
in large enterprise systems), maybe using some a factory on the
initialization line would work:

public static readonly SingletonCounter Instance =
SingeltonCounterFactory.CreateSingletonCounter();

From what I know, this could work because the static member wouldnt be
initialized (and thus the call to the factory would not occur) until a
client accessed the singelton. This could then allow the following during
application start-up:

public void StartUp()
{
// policy enforcement
1. Read necessary factories from config
2. Assign to internal registry
3. Do anything else
4. Initialize singelton
}

There are ways of getting around this too. The singelton counter could talk
to the registry class to get the factories it needs to initialize itself,
though I am less keen on this coupling.

Thanks Yan,

Nick.
 
Hello Mark,

How are things going? I would appreciate it if you could post here to let
me know the status of the issue. If you have any questions or concerns,
please don't hesitate to let me know. I look forward to hearing from you,
and I am happy to be of assistance.

Thanks for participating the community.

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top