Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Singleton with Parameters

Status
Not open for further replies.

jby1

Programmer
Apr 29, 2003
403
GB
Hi

I wish to have a UserProfile class for the client of an appication I am working on. As there will be only one UserProfile per client, I would like to implement this as a Singleton.

I would also like to be able to initialise the UserProfile at creation (parameters such as Username, Role etc), and then have it as a read-only object from then on.

Can anyone suggest a way that I can force the use of parameters for the creation, but then not permit the further setting of these parameters at a later stage?

Thanks
 
Assuming Java, if your singleton is to be used in a multithreaded environment, there is no foolproof way of ensuring that you only ever have one instance of your 'singleton', apart from using a static instance variable assigned by the JVM:-
Code:
public class MyClass {
  private static MyClass instance = new MyClass();

  private MyClass(){};
  public static MyClass getInstance(){
    return instance;
  }
}

Any consumer of the singleton would not know if it is the first to access it, to know to provide your 'creation parameters'.

You could use setters to do the once-only initialisation. Something like:-
Code:
public class MyClass {
  private static MyClass instance = new MyClass();
  private String username;

  private MyClass(){};

  public static MyClass getInstance(){
    return instance;
  }

  public String getUsername(){
    if ( username == null ) throw new IllegalAccessError();
    return username;
  }
  public void setUsername(String username){
    if ( username == null ){
       this.username = username;
    }
  }
}

Once set, the username becomes read-only.

There may be other ways, but this approach is the first to spring to mind.

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top