WBS

static 과 싱글턴

1. Static을 사용하는 코드

static 키워드는 클래스의 특정 필드나 메서드가 인스턴스화 없이도 접근 가능하게 할 때 사용합니다. 모든 객체가 공유하는 자원으로, 별도의 인스턴스가 필요하지 않습니다.

java
코드 복사
class StaticExample {
    // static 필드
    public static int counter = 0;

    // static 메서드
    public static void incrementCounter() {
        counter++;
    }
}

// 사용 예시
public class Main {
    public static void main(String[] args) {
        StaticExample.incrementCounter();
        System.out.println(StaticExample.counter);  // 출력: 1

        StaticExample.incrementCounter();
        System.out.println(StaticExample.counter);  // 출력: 2
    }
}

2. 싱글턴 패턴을 사용하는 코드

싱글턴 패턴은 클래스의 인스턴스를 하나만 생성하고, 그 인스턴스를 전역적으로 사용할 수 있도록 합니다.

java
코드 복사
class Singleton {
    // 싱글턴 인스턴스를 static으로 보유
    private static Singleton instance = null;

    // 외부에서 인스턴스를 생성하지 못하게 생성자를 private으로 선언
    private Singleton() { }

    // 인스턴스를 얻는 static 메서드
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    // 예시 메서드
    public void showMessage() {
        System.out.println("Hello, I am the Singleton instance!");
    }
}

// 사용 예시
public class Main {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        singleton.showMessage();  // 출력: Hello, I am the Singleton instance!
    }
}

차이점 요약

  1. 인스턴스화 여부:
  2. 상태 유지: