Reputation: 27
Note: Even though there are a lot of similar questions, non that i have found answered my question.
Problem: I would like to implement a class in C# which uses the singleton pattern in the following way.
namespace DAL
{
public class CDAL : IDAL
{
/* Singleton Pattern */
private CDAL instance = null;
private CDAL()
{
}
public IDAL getInstance()
{
if (instance != null)
{
return instance;
}
else
{
CDAL.instance = new CDAL();
return CDAL.instance;
}
}
}
}
the problem is that instance and the method getInstance should be static, as i want to 'ask' the class for that instance and not an object. but using c# i can't seem to do anything static in an interface.
how can i solve this?
Upvotes: 0
Views: 1258
Reputation: 13755
It does not make any sense creating an interface with a static member.
Interfaces are a contract while the static member is always accessed by the class name, not the instance name. so briefly your interface does not know which the correct instance implementing the right logic.
in your case you don't need your method getInstance()
to be defined in the interface.
Interface when used with Singleton
is often just for unit testing
purposes
Upvotes: 1
Reputation: 1372
You're right, you cannot do anything static on an interface, since it does not make any sense. Use an abstract class instead of the interface to implement static logic.
Upvotes: 4