Singleton Pattern - dnwls16071/Backend_Summary GitHub Wiki

πŸ“š Singleton Pattern μ„€λͺ…

  • ν•΄λ‹Ή νŒ¨ν„΄μ€ ν”„λ‘œκ·Έλž¨μ—μ„œ νŠΉμ • 클래슀 객체가 단 ν•˜λ‚˜λ§Œ μ‘΄μž¬ν•΄μ•Ό ν•  λ•Œ ν•„μš”ν•˜λ‹€.
  • μΈμŠ€ν„΄μŠ€ μš”μ†Œ(instance)듀은 μƒˆλ‘œμš΄ μΈμŠ€ν„΄μŠ€ 즉, 객체가 생성될 λ•Œλ§ˆλ‹€ ν•¨κ»˜ μƒμ„±λ˜μ–΄ JVM의 νž™ μ˜μ—­μ— μžλ¦¬μž‘κ²Œλœλ‹€.
  • 반면 μŠ€νƒœν‹± μš”μ†Œ(static)듀은 객체 κ°œμˆ˜μ™€ 상관없이 λ”± 1κ°œκ°€ μ‘΄μž¬ν•˜λŠ”λ° JVM의 클래슀 μ˜μ—­μ— μžλ¦¬μž‘κ²Œλœλ‹€.

[Ex1]

public class Theme {

    private static Theme instance;  // ν…Œλ§ˆκ°€ μ—¬λŸ¬ μΈμŠ€ν„΄μŠ€λ₯Ό κ°€μ§„λ‹€λ©΄ μƒνƒœκ°€ λ’€μ£½λ°•μ£½ μ„žμΌ 것이닀.
    private String themeColor;

    private Theme() {               // μƒμ„±μžλ₯Ό private둜 μ„ μ–Έν•΄ μ™ΈλΆ€μ—μ„œ ν˜ΈμΆœν•  수 없도둝 λ°©μ§€ν•œλ‹€.
        this.themeColor = "light";  // Default theme
    }

    public static Theme getInstance() {
        if (instance == null) {
            instance = new Theme();
        }
        return instance;
    }

    public String getThemeColor() {
        return themeColor;
    }
    public void setThemeColor(String themeColor) {
        this.themeColor = themeColor;
    }
}
public class Button {
    private String label;

    public Button(String label) {
        this.label = label;
    }

    public void display() {
        String themeColor = Theme.getInstance().getThemeColor();  // 싱글톀이기 λ•Œλ¬Έμ— 객체가 단 ν•˜λ‚˜λ§Œ 쑴재
        System.out.println(
            "Button [" + label + "] displayed in " + themeColor + " theme."
        );
    }
}

public class TextField {
    private String text;

    public TextField(String text) {
        this.text = text;
    }

    public void display() {
        String themeColor = Theme.getInstance().getThemeColor();
        System.out.println(
            "TextField [" + text + "] displayed in " + themeColor + " theme."
        );
    }
}

public class Label {
    private String text;

    public Label(String text) {
        this.text = text;
    }

    public void display() {
        String themeColor = Theme.getInstance().getThemeColor();
        System.out.println(
            "Label [" + text + "] displayed in " + themeColor + " theme."
        );
    }
}

❗싱글톀 νŒ¨ν„΄μ€ ν…ŒμŠ€νŠΈκ°€ μ–΄λ ΅λ‹€.

싱글톀은 νž™ μ˜μ—­μ—μ„œ μ—¬λŸ¬ 객체둜 μ‘΄μž¬ν•˜λŠ” 것이 μ•„λ‹ˆλΌ 클래슀 μ˜μ—­μ—μ„œ ν•˜λ‚˜μ˜ 객체만으둜 μ‘΄μž¬ν•œλ‹€. κ·Έλ ‡κΈ° λ•Œλ¬Έμ— 클래슀 내에 μ „μ—­ μΈμŠ€ν„΄μŠ€λ₯Ό μœ μ§€ν•˜λ―€λ‘œ ν…ŒμŠ€νŠΈ κ°„ μƒνƒœκ°€ 곡유될 μš°λ €κ°€ μžˆλ‹€. κ·Έλ ‡κ²Œ λœλ‹€λ©΄ λ‹€μŒ ν…ŒμŠ€νŠΈμ— 영ν–₯을 쀄 수 μžˆμ–΄ 독립적인 ν…ŒμŠ€νŠΈ μž‘μ„±μ΄ μ–΄λ €μ›Œμ§„λ‹€.