How to instantiate a Singleton multiple times?

后端 未结 9 1881
醉酒成梦
醉酒成梦 2020-12-19 04:08

I need a singleton in my code. I implemented it in Java and it works well. The reason I did it, is to ensure that in a mulitple environment, there is only one instance of th

9条回答
  •  青春惊慌失措
    2020-12-19 05:00

    Singleton ston=Singleton.getInstance(); will return singleton object. By making use of "ston" object, if we call the method createNewSingleTonInstance() which is written in Singleton class will give new instance.

    public class Singleton {
    
    private String userName;
    private String Password;
    private static Singleton firstInstance=null;
    private Singleton(){}
    
    
    public static synchronized Singleton getInstance(){
        if(firstInstance==null){
            firstInstance=new Singleton();
            firstInstance.setUserName("Prathap");
            firstInstance.setPassword("Mandya");
        }
        return firstInstance;
    }
    
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserName() {
        return userName;
    }
    public void setPassword(String password) {
        Password = password;
    }
    public String getPassword() {
        return Password;
    }
    
    public Singleton createNewSingleTonInstance(){
        Singleton s=new Singleton();
        s.setUserName("ASDF");
        s.setPassword("QWER");
        return s;
    }
    }
    

提交回复
热议问题