Java: Singleton in the same class

4

I have a doubt about the fact that it is possible to create a Singleton in a class where I have getters, setters and the Singleton I want to create it in the constructor, if possible you could give me an example please. Thanks

public class CheckIn{

  private int folio;
  private String customer;
  private String delivered;
  private ArrayList<Bitmap> images;

  public CheckIn(int folio, String customer, String delivered){
    this.folio = folio;
    this.customer = customer;
    this.delivered = delivered;
    //AQUI QUIERO IMPLEMENTAR EL SINGLETON
  }

  public int getFolio() {
    return folio;
  }

  public void setFolio(int folio) {
    this.folio = folio;
  }

  public String getCustomer() {
    return customer;
  }

  public void setCustomer(String customer) {
    this.customer = customer;
  }

  public String getDelivered() {
    return delivered;
  }

  public void setDelivered(String delivered) {
    this.delivered = delivered;
  }

  public ArrayList<Bitmap> getImages() {
    return images;
  }

  public void setImages(ArrayList<Bitmap> bitmapArray) {
    this.images = bitmapArray;
  }

}
    
asked by Javier fr 01.12.2016 в 02:05
source

2 answers

1

A Singleton needs a static method to install it, to ensure that there is only one instance. The static modifier is not yet allowed within member methods or their constructors. So what you can do is declare the Singleton as your own class, but install it in the constructor.

public class Singleton {
    // campo estatico para recibir la unica instancia del Singleton
    private static final Singleton s = null;

    private Singleton() {
        // lo que necesites de código
    }

    public synchronized static Singleton getInstance() {
        if (s==null) s = new Singleton(); // instar el Singleton si no hay todavía
        return s;
    }
}

And in your constructor:

public CheckIn(int folio, String customer, String delivered){
    this.folio = folio;
    this.customer = customer;
    this.delivered = delivered;
    //AQUI QUIERO IMPLEMENTAR EL SINGLETON
    Singleton s = Singleton.getInstance();
}
    
answered by 03.04.2017 в 21:07
-1
public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    // El constructor privado no permite que se genere un constructor por defecto.
    // (con mismo modificador de acceso que la definición de la clase) 
    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}
    
answered by 01.12.2016 в 03:03