Skip to content

Instantly share code, notes, and snippets.

@tomlins
Last active December 29, 2015 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomlins/7670790 to your computer and use it in GitHub Desktop.
Save tomlins/7670790 to your computer and use it in GitHub Desktop.
An example of using an Enum class as a Singleton
// Using an Enum as a Singleton
//
public enum TestDAO {
// Our one and only instance
instance;
private DataSource dataSource = new DataSource();
// private constructor to prevent any instantiations
private TestDAO() {
dataSource.setName("myDatabaseName");
dataSource.setUrl("jdbc:/myUrl/next/other/");
}
public DataSource getDataSource() {
return dataSource;
}
public void moreUsefulMethodsHere(String... strings) {
// ** Cool stuff ??
}
}
// The app
public class Main {
public static void main(String... args) {
// Obtain the only instance...
DataSource ds = TestDAO.instance.getDataSource();
System.out.println("URL = " + ds.getUrl());
}
}
// Simple bean
public class DataSource {
private String url;
private String name;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment