singleton design pattern vs static class

공용 데이터를 저장하여 사용하고자 할 때, singleton design pattern이나 inner static class를 사용한다.

싱글톤 패턴 (Singleton design pattern) -싱글톤 패턴이란 single instance object(해당 클래스의 인스턴스 하나)가 만들어지고, 어디서든지 그 싱글톤에 접근할 수 있도록 하기 위한 패턴

public final class SiteStructureSingletonPattern {
    private Object[] data = new Object[10];

    private static SiteStructureSingletonPattern instance = new SiteStructureSingletonPattern(); // private static member인 instance
    public static SiteStructureSingletonPattern getInstance() { // getInstance() 메소드를 사용하여 instance 객체 사용
        return instance;
    }
    private SiteStructureSingletonPattern() {
        System.out.println("SiteStructureSingletonPattern constructor");
        for(int i=0; i<10; i++) {
            data[i] = i+1;
        }
    }
    public void print() {
        System.out.print("SiteStructureSingletonPattern data=");
        for(int i=0; i<10; i++) {
            System.out.print(" " + data[i]);
        }
        System.out.println();
    }
}
public class SiteStructureStaticClass {
    private Object[] data = new Object[10];

    private static class SiteStructureStatic { // inner static class
        private static final SiteStructureStaticClass instance = new SiteStructureStaticClass();
    }
    public static SiteStructureStaticClass getInstance() {
        return SiteStructureStatic.instance;
    }
    private SiteStructureStaticClass() {
        System.out.println("SiteStructureStaticClass constructor");
        for(int i=0; i<10; i++) {
            data[i] = i+1;
        }
    }

    public void print() {
        System.out.print("SiteStructureStaticClass data=");
        for(int i=0; i<10; i++) {
            System.out.print(" " + data[i]);
        }
        System.out.println();
    }
}
public class StaticClassSingletonPatternTest {

    public static void main(String[] args) {
        SiteStructureSingletonPattern instance = SiteStructureSingletonPattern.getInstance();
        instance.print();
        instance = SiteStructureSingletonPattern.getInstance();
        instance.print();

        SiteStructureStaticClass instance2 = SiteStructureStaticClass.getInstance();
        instance2.print();
        instance2 = SiteStructureStaticClass.getInstance();
        instance2.print();
    }
}