java - How to create a singleton class using enum -
i trying create singleton class in java. best available solution java5 , above versions seems using enum. not sure how convert class singleton class using enum. following simplified class:
public class employee { private int id; private string name; public employee() {} public int getid() { return id; } public void setid( int id ) { this.id = id; } public string getname() { return name; } public void setname( string name ) { this.name = name; } } when searched answers in net found following code:
public enum easysingleton{ instance; } but class variables , methods? not sure how implement this. know can provide methods enum variables go? on appreciated.
p.s.: please don't debate if singleton evil or anti-pattern. curious on how create singleton using enum.
the differences between class , enum not big. changed first line of code public enum instead of public class , added name of instance.
public enum employee { // changed "class" "enum" instance; // added name of (single) instance private int id; private string name; employee() {} // removed "public" public int getid() { return id; } public void setid( int id ) { this.id = id; } public string getname() { return name; } public void setname( string name ) { this.name = name; } } please keep in mind, singeltons, enum instances, static things might hinder later on, if want run code several times in 1 vm. consider creating instance of employee in main class , pass through application.
beside that, enums have other special features:
- you cannot
extendclass (onlyimplements) - some predefined methods (like
static values(),getname()) available - constructors can package private, or private
Comments
Post a Comment