Exists only to defeat instantiation in singleton - singleton

In many of the Singleton examples, I have come across constructor having comment as "Exists only to defeat instantiation", can you please give me details and explain more about it.

It's common to create a private constructor when implementing the Singleton pattern so that the default constructor cannot be used to instantiate multiple Singleton objects.
See the example from Wikipedia's Singleton pattern article.
public class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() { }
public static synchronized SingletonDemo getInstance() {
if (instance == null) {
instance = new SingletonDemo ();
}
return instance;
}
}
By making a private constructor, you insure that the compiler can't make a default constructor with the same signature, which forces any client code to call the getInstance() method.

Related

Is there a better alternative to check for collections with members with optional interfaces?

I have a configuration registry class which holds a collection of configuration classes with a certain interface. These classes can also have an optional interface. So these classes may look like this in pseudocode:
class ConfigurationRegistry {
private ModuleConfiguration[];
public function ConfigurationRegistry(ModuleConfiguration[] collection) {
this.collection = collection;
}
public function getCollection() {
return this.collection;
}
}
class ConfigurationClass1 implements ModuleConfiguration, SpecificConfiguration {
public function moduleMethod() {
// do something
}
public function specificMethod() {
// do specific thing
}
}
class ConfigurationClass2 implements ModuleConfiguration {
public function moduleMethod() {
// do something
}
}
public interface ModuleConfiguration {
public function moduleMethod();
}
public interface SpecificConfiguration {
public function specificMethod();
}
In my client code I would like to use these configuration classes. Sometimes I need the whole collection of configuration classes and sometimes I only need to collection of configuration classes which implement the SpecificConfiguration interface.
I could filter the collection method by using instanceof or I could loop through the collection and check whether the class implements the interface. But I've read quite a few articles stating online that using instanceof in this case is not considered a good practice.
My question is: is my implementation a good design? If not, do you have any suggestions how I could redesign or improve this?

Avoiding instance construction of return type while generating stub for method

I have issue while trying to mock method that returns instance of abstract class with Rhino Mocks. Issue is that MammalBase constructor is invoked while stub is created and I would like to avoid that. All source code in question is locked for editing and only tests can be changed.
Eventually, base class is processing something by type attributes in constructor, and throws exception if no adequate attributes are detected. That causes a extensive logging.
My hope is to remove unnecessary logs from tests.
Is it possible to instruct Rhino Mocks not to instantiate return type (MammalBase) when it creates proxy while creating a stub?
Is explicit attribute or type setting possible for return value while Rhino creates stub for method with abstract class instance as return type?
Is avoiding constructor even possible without making stubbed method return interface?
I found that issue does not exist if:
1. Stubbed method returns array like MammalBase[],
2. Stubbed method returns derivate class like "Human" first, since no more constructors of base class are invoked.
Thanks in advance!
(Code sample)
public interface IDetermineMammalByType
{
MammalBase DetermineMammalByType(MammalBase creature);
}
public abstract class MammalBase
{
protected MammalBase()
{
CustomAttribute[] attributes = (CustomAttribute[])Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute));
if (!attributes.Any(x=> x as CustomAttribute != null))
{
//This causes issue
throw new Exception();
}
}
}
[CustomAttribute()]
public class Human : MammalBase { }
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)]
public class CustomAttribute : System.Attribute
{
public CustomAttribute() { }
}
public class MammalDetector : IDetermineMammalByType
{
public MammalBase DetermineMammalByType(MammalBase creature)
{
//Some logic
return null;
}
}
//TEST
[TestMethod()]
public void DetermineMammalByTypeTest()
{
IDetermineMammalByType myTest = MockRepository.GenerateStub<IDetermineMammalByType>();
var creature = new Human();
//Here it fails while mocking method
myTest.Stub(x => x.DetermineMammalByType(creature)).Return(new Human());
}

how to ensure only one instance of singleton class is created?

I have read the concepts of Singleton design pattern and understood that for making a class singleton we have to do the following steps :
1)Private constructor to restrict instantiation of the class from other classes.
2)Private static variable of the same class that is the only instance of the class.
3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
So my class looks like this :
public class Singleton {
private static Singleton singleton =new Singleton();;
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){
System.out.println("Creating new now");
}
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
public void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
But here how we can ensure that only one instance of Singleton is created ? Suppose I have 2 classes Singletondemo1 and Singletondemo2.
In Singletondemo1 , I am calling the getInstance() and craete an object. Same way I can do that in Singletondemo2 also.
So how we will ensure only object is created and also it is thread safe.

How does a WCF proxy implement ICommunicationObject if it's methods aren't visible?

How does a WCF channel (created via ChannelFactory) implement ICommunicationObject, but doesn't expose the Close() method, for example, unless you cast the proxy to ICommunicationObject? Does that make sense?
I got to thinking about that on the way home today and couldn't figure it out in my head. Maybe I'm asking the wrong question? Maybe I'm asking a stupid question? :)
Is it some kind of ninja trick?
This is done via Explicit Interface Implementation.
Suppose you have an interface, like so:
public interface IFoo
{
void Foo();
}
You can implement this normally:
public class Bar : IFoo
{
public void Foo() {} // Implicit interface implementation
}
Alternatively, you can implement the interface members explicitly, which requires the cast:
public class Baz : IFoo
{
void IFoo.Foo() {} // This will require casting the object to IFoo to call
}
This can be very useful at times. For example, it is often done to implement IDisposable in classes where the preferred API would be to call .Close(), for example. By implementing IDisposable explicitly, you "hide" the Dispose() method, but still allow the class instance to be used via a using statement.
The Channel class implements the ICommunicationObject interface explicitly. Here's an example demonstrating the difference between explicit interface implementation and implicit interface implementation:
internal interface IExample
{
void DoSomething();
}
class ImplicitExample : IExample
{
public void DoSomething()
{
// ...
}
}
class ExplicitExample : IExample
{
void IExample.DoSomething()
{
// ...
}
}
class Consumer
{
void Demo()
{
var explicitExample = new ExplicitExample();
// explicitExample.DoSomething(); <-- won't compile
((IExample)explicitExample).DoSomething(); // <-- compiles
var implicitExample = new ImplicitExample();
implicitExample.DoSomething(); // <-- compiles
}
}
Here is a link to the an MSDN article on this subject: http://msdn.microsoft.com/en-us/library/ms173157.aspx

Singleton class implementation in Multi threaded environment

In Multithreaded environment where there are 50 concurrent threads are accessing a singleton object.
Can it lead to a performance issue as there can be situation threads can be blocked as all the threads will try to access a single instance?
concurrent access will not be an issue. but you have to be careful with synchronization of such access. i.e. (I assume we talk about java)
class MySingletonFactoryClass
{
public static MySingleton getInstnace()
{
synchronized(MySingletonFactoryClass.class) {
if(instance == null)
instance = new MySingleton();
return instance;
}
}
}
There will not be a performance issue and you do NOT need to synchronize anything, nor wrap it in any way, just implement it the regular recommended way:
public class MySingleton {
private static MySingleton _instance;
private MySingleton() {
//initialize it here
}
public static MySingleton getInstance() { return _instance; }
//other methods of the class here
}