tags:

views:

85

answers:

3

i am developing windows form application . i need to implement single ton design project. when implementing the singleton in two classes which are in same package it works correctly but implementing the two classes in different package by justing creating object for both classes in that class. how can I implement that.here code ex

public class Singleton
{
   private static Singleton instance;
   B b=new B();
   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }

public void a()
{
}
b.c();
}


public class B
{
SingleTon single=new SingleTon.Instance;
single.a()
public void c()
{
}
}
A: 

The code you wrote here should work(sure Instence is method i suppose?..), also the different projects shouldn't be a problem, because you have public accessor everywhere, where is needed. May be you have a bit different problem?

nihi_l_ist
-1 This code will not even compile, much less "should work".
drharris
A: 

The idea of the Singleton pattern is to use the same object and not to create a new one. Apart from all the syntax errors in you code snippet, you shouldn't be trying to create a 'new' Singleton. Instead in class B you should have a line like this: private Singleton singleton = Singleton.Instance; The way you wrote it, it wouldn't compile because the Singleton's constructor is not visible in class B.

Radoslav Hristov
A: 

First, if you are exposing this outside the project, please consider using Abstract Factory Pattern instead of Singleton. See my own question for why this can get out of hand.

But, if you must, start small:

public class Singleton
{
    private static Singleton instance = new Singleton();
    private Singleton() { }
    public static Singleton Instance { get { return instance; } }
    public void a(B b)
    {
        b.c();
    }
}

public class B
{
    static void Main()
    {
        B b = new B();
        Singleton.Instance.a(b);
    }

    public void c()
    {
        // whatever you want it to do
    }
}

But, you should be forewarned that this creates a very tight coupling (almost a deadlock) between Singleton and B, which means you (as the library creator) must know about every class B that will be using this. Consider a very different design here, because this is a horrible way to implement Singleton. I almost hate to even post this code, but am doing so with this disclaimer in tow.

drharris