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);
}}

解决方案 »

  1.   

    public class Wife {
    public static Wife onewife = null;
    private static  Wife marriage(){//用private
    if(null == onewife){
    onewife = new Wife();//不能重新定义Wife
    }
    return onewife;
    }}
      

  2.   

    定义为private 的话,那个Man 的类就不能访问了,
    onewife = new Wife();//不能重新定义Wife
    这是new 一个实例吧,不叫重新定义吧.
      

  3.   

    单态模式的目的是要保证某个类只有一个实例存在。要保证这一点,也就是说该类不能被任何自身以外的类创建实例(new)。
    实现单态模式的类,构造方法必定是私有的。因此,单态模式是不能通过继承来扩展的。
      

  4.   

    看看这个单例模式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);
    }}