-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonExample.java
More file actions
35 lines (27 loc) · 819 Bytes
/
Copy pathSingletonExample.java
File metadata and controls
35 lines (27 loc) · 819 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Day 32 - Design Patterns: Singleton
*/
public class SingletonExample {
static class Database {
private static Database instance;
private String connectionString;
private Database() {
connectionString = "Connected";
}
static synchronized Database getInstance() {
if (instance == null) {
instance = new Database();
}
return instance;
}
void query(String sql) {
System.out.println("Executing: " + sql);
}
}
public static void main(String[] args) {
Database db1 = Database.getInstance();
Database db2 = Database.getInstance();
System.out.println("Same instance: " + (db1 == db2));
db1.query("SELECT * FROM users");
}
}