์ฑ๊ธํค ํจํด์ ์์ฑ ํจํด ์ค ํ๋๋ก, ํ๋ก๊ทธ๋จ ๋ด์์ ํน์ ์ธ์คํด์ค๊ฐ ๋จ ํ๋์์ ๋ณด์ฅํ๋ ํจํด์ด๋ค. ๋ชจ๋ ๊ฐ์ฒด๊ฐ ๋จ ํ๋์ ๊ฐ์ฒด๋ฅผ ๊ณต์ ํ๋ค.
public class Singleton {
private static Singleton instance;
// Private constructor to prevent direct instantiation
private Singleton() {
// Initialization if needed
}
// Static method to provide access to the instance
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
// Other methods or properties can be added here
public void someMethod() {
System.out.println("Singleton method called.");
}
}
public class Main {
public static void main(String[] args) {
// Accessing the Singleton instance
Singleton singletonInstance1 = Singleton.getInstance();
Singleton singletonInstance2 = Singleton.getInstance();
// Both instances will be the same object
System.out.println(singletonInstance1 == singletonInstance2); // Output: true
// Using the Singleton's methods
singletonInstance1.someMethod(); // Output: Singleton method called.
singletonInstance2.someMethod(); // Output: Singleton method called.
}
}
์์ฑ์์ ์ ๊ทผ ์ ํ์ `private`์ผ๋ก ๋์ด ๋ค๋ฅธ ํด๋์ค์์ ์์ฑ์๋ฅผ ํธ์ถํ์ง ๋ชปํ๋๋ก ๋ง๋๋ค. `getInstance()` ๋ฉ์๋์์ ์๊ธฐ ์์ ๊ฐ์ฒด๋ฅผ ์์ฑํ์ฌ ๋ฉค๋ฒ ํ๋์ ํ ๋นํ ๋ค `private` `static`์ผ๋ก ์ ์ธ๋ ๋ฉค๋ฒ ํ๋๋ฅผ ๋ฐํํ๋ค.
์ด๋ `instance`๋ผ๋ ๋ฉค๋ฒ ํ๋๋ `private`์ด๊ธฐ ๋๋ฌธ์ ๋ค๋ฅธ ๊ณณ์์ ํด๋น ํด๋์ค ์ด๋ฆ์ผ๋ก ์ง์ ์ฐธ์กฐ๋ ์ผ๋ ์์ผ๋ฏ๋ก ๊ตณ์ด `static`์ผ๋ก ์ ์ธ๋์ง ์์๋ ๊ด์ฐฎ์ ๋ณด์ธ๋ค!
์ static์ด์ด์ผ ํ ๊น?
์์ฑ์์ ์ ๊ทผ ์ ํ์ด `private`์ผ๋ก ์ ํ ๋์ด์๋ ์ํฉ์์, ํด๋น ๊ฐ์ฒด๋ฅผ ์ป์ผ๋ ค๋ฉด ๋ฐ๋์ `getInstance()` ๋ฉ์๋๋ฅผ ํธ์ถํด์ผ ํ๋ค. ์ด๋ `getInstance()`๊ฐ `static`์ผ๋ก ์ ์ธ๋์ด ์์ผ๋ฏ๋ก ํด๋น ๋ฉ์๋ ๋ด๋ถ์์๋ non-static ๋ฉค๋ฒ๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
`static` ์ฑ์ง์ ๊ฐ์ง ๋ฉค๋ฒ๋ ํด๋์ค์ ์ข ์๋๋ฏ๋ก ํ๋ก๊ทธ๋จ ์์ฑ ์ฆ์ ํด๋์ค ๋ฐ ์ธํฐํ์ด์ค ๋ฑ์ ๋ฐ์ดํฐ์ ํจ๊ป JVM ๋ฉ๋ชจ๋ฆฌ ์์ญ์ Static area(Method area)์ ์ฌ๋ผ๊ฐ๊ฒ ๋๋ฏ๋ก ํด๋์ค ์ด๋ฆ์ ํตํด ์์ ์ฐธ์กฐํ ์ ์์ผ๋ฉฐ ๋ชจ๋ ๊ฐ์ฒด๊ฐ ํด๋น ๊ฐ์ ๊ณต์ ํ๋ค. ๋ฐ๋ฉด ์ธ์คํด์ค ๋ฉค๋ฒ๋ ๋ฐ๋์ ๊ฐ์ฒด ์์ฑ ํ Heap ์์ญ์ ์ฌ๋ผ๊ฐ๊ณ ๋์์ผ ์ฌ์ฉํ ์ ์๋ค. ๋ฐ๋ผ์ `static` ์ผ๋ก ์ ์ธ๋ ๋ฉ์๋์์ ์ธ์คํด์ค ๋ฉค๋ฒ๋ฅผ ์ฌ์ฉํ๋ ค๊ณ ํ ๋ ๊ทธ ์์ ์ ํด๋น ์ธ์คํด์ค๊ฐ ์์ฑ๋์ง ์์์ ๊ฒฝ์ฐ ํด๋น ํ๋๋ ์กด์ฌํ์ง ์๋ ํ๋๋ก ๊ฐ์ฃผ๋๋ฏ๋ก `static` ๋ฉ์๋ ๋ด๋ถ์์ ์ธ์คํด์ค ๋ฉค๋ฒ๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
'CS > ๋์์ธ ํจํด' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋์์ธ ํจํด] ์ํ(State) ํจํด (0) | 2024.01.17 |
---|---|
[๋์์ธ ํจํด] ๋ฐ์ฝ๋ ์ดํฐ(Decorator) ํจํด (0) | 2024.01.13 |
[๋์์ธ ํจํด] ํ๋ก์(Proxy) ํจํด (0) | 2024.01.13 |
[๋์์ธ ํจํด] ํฉํ ๋ฆฌ ๋ฉ์๋(Factory Method) ํจํด (0) | 2024.01.10 |