日期:2014-05-20  浏览次数:20620 次

我的单子模式为什么不行?!各位大哥请帮忙看一下!
package   singleton;

public   class   Wife   {
public   static   Wife   onewife   =   null;
protected   static     Wife   marriage(){
if(null   ==   onewife){
Wife   onewife   =   new   Wife();
}
return   onewife;
}

}

package   singleton;

public   class   Man   extends   Wife   {

/**
  *   @param   args
  */
public   static   void   main(String[]   args)   {
//   TODO   Auto-generated   method   stub
Man   m1   =   new   Man();
Man   m2   =   new   Man();
m1.marriage();
m2.marriage();
System.out.println(m1==m2);
}

}


------解决方案--------------------
看看这个单例模式

public class Singleton {
private static Singleton obj=null;

private Singleton(){

}

public synchronized static Singleton getInstance(){
if(obj==null)
obj = new Singleton();
return obj;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1==s2);
}

}