Singleton ํจํด
์ ํ๋ฆฌ์ผ์ด์ ์์ ์ธ์คํด์ค๋ฅผ ํ๋๋ง ๋ง๋ค์ด ์ฌ์ฉํ๊ธฐ ์ํ ํจํด์ด๋ค.
์ปค๋ฅ์ ํ, ์ค๋ ๋ ํ, ๋๋ฐ์ด์ค ์ค์ ๊ฐ์ฒด ๋ฑ์ ๊ฒฝ์ฐ, ์ธ์คํด์ค๋ฅผ ์ฌ๋ฌ ๊ฐ ๋ง๋ค๊ฒํ๋ฉด ์์์ ๋ญ๋นํ๊ฒ ๋๊ฑฐ๋ ๋ฒ๊ทธ๋ฅผ ๋ฐ์์ํฌ ์ ์์ผ๋ฏ๋ก ์ค์ง ํ๋๋ง ์์ฑํ๊ณ ๊ทธ ์ธ์คํด์ค๋ฅผ ์ฌ์ฉํ๋๋ก ํ๋ ๊ฒ์ด ๋ชฉ์ ์ด๋ค.
๊ตฌํ
ํ๋์ ์ธ์คํด์ค๋ง์ ์ ์งํ๊ธฐ ์ํด ์ธ์คํด์ค ์์ฑ์ ํน๋ณํ ์ ์ฝ์ ๊ฑธ์ด๋ฌ์ผํ๋ค.
- new๋ฅผ ์คํํ ์ ์๋๋ก ์์ฑ์์ private ์ ๊ทผ ์ ์ด์๋ฅผ ์ง์
- ์ ์ผํ ๋จ์ผ ๊ฐ์ฒด๋ฅผ ๋ฐํํ ์ ์๋๋ก ์ ์ ๋ฉ์๋๋ฅผ ์ง์.
- ์ ์ผํ ๋จ์ผ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ ์ ์ ์ฐธ์กฐ๋ณ์ ํ์
public class Singleton {
private static Singleton singletonObject;
private Singleton() {}
public static Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
}์ ์ฝ๋๋ ๋ฉํฐ ์ค๋ ๋ฉํ๊ฒฝ์์ ์ฑ๊ธํด ํจํด์ ์ ์ฉํ ๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ๋ค. ๋์์ ์ ๊ทผํ๋ค๊ฐ ํ๋๋ง ์์ฑ๋์ด์ผํ๋ ์ธ์คํด์ค๊ฐ ๋๊ฐ ์์ฑ๋ ์ ์๊ธฐ๋๋ฌธ์ด๋ค. ๋ฐ๋ผ์ getInstance() ๋ฉ์๋๋ฅผ ๋๊ธฐํ ์์ผ์ผ ํ๋ค.
public class Singleton {
private static Singleton singletonObject;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
}์ข ๋ ํจ์จ์ ์ผ๋ก ํ๋ ค๋ฉด, DCL(double checking locking)์ ์จ์ getInstance() ์์ ๋๊ธฐํ ๋๋ ์์ญ์ ์ค์ผ ์ ์๋ค.
public class Singleton {
private static volatile Singleton singletonObject;
private Singleton() {}
public static Singleton getInstance() {
if (singletonObject == null) {
synchronized (Singleton.class) {
if(singletonObject == null) {
singletonObject = new Singleton();
}
}
}
return singletonObject;
}
}์ด๋ ์ ์ฝ๋๋, ๋ฉํฐ์ฝ์ด ํ๊ฒฝ์์ ํ๋์ CPU๋ฅผ ์ ์ธํ๊ณ ๋ ๋ค๋ฅธ CPU๊ฐ lock์ด ๊ฑธ๋ฆฌ๊ฒ ๋๋ค. ๋ฐ๋ผ์ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ด ํ์ํ๋ค.
public class Singleton {
private static volatile Singleton singletonObject = new Singleton();
private Singleton() {}
public static Singleton getSingletonObject() {
return singletonObject;
}
}volatile : ์ปดํ์ผ๋ฌ๊ฐ ํน์ ๋ณ์์ ๋ํด ์ตํฐ๋ง์ด์ ธ๊ฐ ์บ์ฑ์ ์ ์ฉํ์ง ๋ชปํ๋๋ก ํ๋ ํค์๋์ด๋ค.