java singleton如何扩展其他类? [英] how java singleton can extends other classes?

查看:92
本文介绍了java singleton如何扩展其他类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java singleton的新手,我想让我的类单例,所以我在我的代码中有一个它的实例。我想成为单例的类是扩展另一个类,它的构造函数有两个条目,条目也是单例!



下面是代码,我做了什么!但这不正确!我怎么能写我的单身人士



I am new to java singleton, I want to make my class singleton, so that I have one instance of it in my code. The class which I want to be singleton is extend another class which its constructor have two entries, and entries are also singleton!

Below code is, what I have done! but it is not correct! how can I write my singleton

public class Singleton extends Parent{
private Ui ui;
private Store store;
private singleton(Ui ui, Store store) {
    super(ui, store);
    // TODO Auto-generated constructor stub
}
private static class singletonHolder() {
    // My problem is here: how to set value for super class?!
    public static final singleton INSTANCE = new singleton();
}

public static singleton getInstance() {
    return singletonHolder.INSTANCE;
}

protected Object readResolve() {
    return getInstance();
}
public void SetStore(Store dstore){
    store = dstore;
}
public void SetUi(Ui uid){
    ui = uid;
} 
}

推荐答案

假设Ui和Store类也实现为Singleton,你可以做如下。



Assuming that the Ui and Store classes are also implemented as Singleton, you could do it as follows.

public class Singleton extends Parent{
  private Ui ui;
  private Store store;

  // Static field to hold the singleton instance 
  private static final singleton INSTANCE;

  // This is a static constructor. It will be executed once, when the class is 
  // loaded.  Use this to create an instance of your class for the singleton
  static {

     INSTANCE =  new Singleton(Ui.getInstance(), Store.getInstance());
  }

  // This is the constructor. You HAVE to pass the parameters to the base 
  // class (Parent), See the static constructor above.
  private Singleton(Ui ui, Store store) {
      super(ui, store);
  }

  public static singleton getInstance() {

      return INSTANCE;
  }
 
  protected Object readResolve() {

      return getInstance();
  }

  public void SetStore(Store dstore){

      store = dstore;
  }

  public void SetUi(Ui uid){

      ui = uid;
  } 
}


这篇关于java singleton如何扩展其他类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆