Skip to content

Commit 1cfbf30

Browse files
committed
Fixes missing eager/lazy initialization examples for Hacktoberfest contributors
1 parent ede37bd commit 1cfbf30

File tree

6 files changed

+256
-1
lines changed

6 files changed

+256
-1
lines changed

singleton/README.md

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,51 @@ Sequence diagram
3939

4040
## Programmatic Example of Singleton Pattern in Java
4141

42+
### 1. Eager Initialization
43+
44+
The instance is created at class loading time. Thread-safe but may waste memory if never used.
45+
46+
```java
47+
public final class EagerInitializedSingleton {
48+
private static final EagerInitializedSingleton INSTANCE = new EagerInitializedSingleton();
49+
50+
private EagerInitializedSingleton() {
51+
if (INSTANCE != null) {
52+
throw new IllegalStateException("Singleton already initialized");
53+
}
54+
}
55+
56+
public static EagerInitializedSingleton getInstance() {
57+
return INSTANCE;
58+
}
59+
}
60+
```
61+
62+
### 2. Lazy Initialization
63+
64+
The instance is created only when first requested. Memory efficient but requires synchronization.
65+
66+
```java
67+
public final class LazyInitializedSingleton {
68+
private static LazyInitializedSingleton instance;
69+
70+
private LazyInitializedSingleton() {
71+
if (instance != null) {
72+
throw new IllegalStateException("Singleton already initialized");
73+
}
74+
}
75+
76+
public static synchronized LazyInitializedSingleton getInstance() {
77+
if (instance == null) {
78+
instance = new LazyInitializedSingleton();
79+
}
80+
return instance;
81+
}
82+
}
83+
```
84+
85+
### 3. Enum Singleton (Recommended)
86+
4287
Joshua Bloch, Effective Java 2nd Edition p.18
4388

4489
> A single-element enum type is the best way to implement a singleton
@@ -49,7 +94,7 @@ public enum EnumIvoryTower {
4994
}
5095
```
5196

52-
Then in order to use:
97+
Usage example:
5398

5499
```java
55100
var enumIvoryTower1 = EnumIvoryTower.INSTANCE;

singleton/src/main/java/com/iluwatar/singleton/App.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,22 @@ public class App {
7272
*/
7373
public static void main(String[] args) {
7474

75+
// Eager Initialization - Simple and clear example
76+
LOGGER.info("=== Eager Initialization ===");
77+
var eager1 = EagerInitializedSingleton.getInstance();
78+
var eager2 = EagerInitializedSingleton.getInstance();
79+
LOGGER.info("eager1={}", eager1);
80+
LOGGER.info("eager2={}", eager2);
81+
LOGGER.info("Same instance: {}", eager1 == eager2);
82+
83+
// Lazy Initialization - Simple and clear example
84+
LOGGER.info("=== Lazy Initialization ===");
85+
var lazy1 = LazyInitializedSingleton.getInstance();
86+
var lazy2 = LazyInitializedSingleton.getInstance();
87+
LOGGER.info("lazy1={}", lazy1);
88+
LOGGER.info("lazy2={}", lazy2);
89+
LOGGER.info("Same instance: {}", lazy1 == lazy2);
90+
7591
// eagerly initialized singleton
7692
var ivoryTower1 = IvoryTower.getInstance();
7793
var ivoryTower2 = IvoryTower.getInstance();
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.singleton;
26+
27+
/**
28+
* Eager Initialization Singleton.
29+
* Instance is created at class loading time.
30+
* Thread-safe by default but may waste memory if instance is never used.
31+
*/
32+
public final class EagerInitializedSingleton {
33+
34+
/** Instance created at class loading time. */
35+
private static final EagerInitializedSingleton INSTANCE = new EagerInitializedSingleton();
36+
37+
/** Private constructor to prevent instantiation. */
38+
private EagerInitializedSingleton() {
39+
// Prevent reflection attacks
40+
if (INSTANCE != null) {
41+
throw new IllegalStateException("Singleton already initialized");
42+
}
43+
}
44+
45+
/**
46+
* Returns the singleton instance.
47+
*
48+
* @return the singleton instance
49+
*/
50+
public static EagerInitializedSingleton getInstance() {
51+
return INSTANCE;
52+
}
53+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.singleton;
26+
27+
/**
28+
* Lazy Initialization Singleton.
29+
* Instance is created only when first requested.
30+
* Memory efficient but requires synchronization for thread safety.
31+
*/
32+
public final class LazyInitializedSingleton {
33+
34+
/** Instance variable, initialized only when needed. */
35+
private static LazyInitializedSingleton instance;
36+
37+
/** Private constructor to prevent instantiation. */
38+
private LazyInitializedSingleton() {
39+
// Prevent reflection attacks
40+
if (instance != null) {
41+
throw new IllegalStateException("Singleton already initialized");
42+
}
43+
}
44+
45+
/**
46+
* Returns the singleton instance, creating it if necessary.
47+
* Synchronized to ensure thread safety.
48+
*
49+
* @return the singleton instance
50+
*/
51+
public static synchronized LazyInitializedSingleton getInstance() {
52+
if (instance == null) {
53+
instance = new LazyInitializedSingleton();
54+
}
55+
return instance;
56+
}
57+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.singleton;
26+
27+
import static org.junit.jupiter.api.Assertions.assertSame;
28+
29+
import org.junit.jupiter.api.Test;
30+
31+
/**
32+
* Tests for {@link EagerInitializedSingleton}.
33+
*/
34+
class EagerInitializedSingletonTest {
35+
36+
@Test
37+
void testSingletonInstance() {
38+
var instance1 = EagerInitializedSingleton.getInstance();
39+
var instance2 = EagerInitializedSingleton.getInstance();
40+
assertSame(instance1, instance2);
41+
}
42+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
package com.iluwatar.singleton;
26+
27+
import static org.junit.jupiter.api.Assertions.assertSame;
28+
29+
import org.junit.jupiter.api.Test;
30+
31+
/**
32+
* Tests for {@link LazyInitializedSingleton}.
33+
*/
34+
class LazyInitializedSingletonTest {
35+
36+
@Test
37+
void testSingletonInstance() {
38+
var instance1 = LazyInitializedSingleton.getInstance();
39+
var instance2 = LazyInitializedSingleton.getInstance();
40+
assertSame(instance1, instance2);
41+
}
42+
}

0 commit comments

Comments
 (0)