Last active
December 29, 2015 12:29
-
-
Save tomlins/7670790 to your computer and use it in GitHub Desktop.
An example of using an Enum class as a Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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