我是android开发的新手,感谢任何帮助。我有多个必须访问一个 java 类的 android 活动。此类具有同步的 getter 和 setter,但我在跨活动创建此类的单个实例时遇到问题。有什么方法可以轻松做到这一点?
			
			3875 次
		
2 回答
            2        
        
		
您需要的是“单例”模式:
public final class Singleton {
    private final static Singleton ourInstance = new Singleton();
    public static Singleton getInstance() {
        return ourInstance;
    }
    // Contructor is private, so it won't be possible 
    // to create instance of this class from outside of it.
    private Singleton() {
    }
}
现在在您的孩子班级中,只需使用:
Singleton.getInstance()
访问此类的一个单一对象。
于 2013-03-07T13:30:40.810   回答
    
    
            0        
        
		
您可以使用单例设计模式。这是在java中实现它的一种方法
public class Singleton 
{
  private static Singleton uniqInstance;
  private Singleton() 
  {
  }
  public static synchronized Singleton getInstance() 
  {
    if (uniqInstance == null) {
      uniqInstance = new Singleton();
    }
  return uniqInstance;
  } 
 // other useful methods here
} 
于 2013-03-07T13:30:27.420   回答