여러가지 디자인 패턴 - Singleton Pattern (싱글톤 패턴)

이진석·2022년 9월 7일
1
post-thumbnail

20220907

한 번에 끝내는 Java/Spring 웹 개발 마스터


1) SocketClient

package com.company.design.singleton;

public class SocketClient {

    private static SocketClient socketClient = null;

    private SocketClient() {}

    public static SocketClient getInstance() {

        if(socketClient == null) {
            socketClient = new SocketClient();
        }
        return socketClient;
    }

    public void connect() {
        System.out.println("Connect");
    }
}

2) Aclazz

package com.company.design.singleton;

public class Aclazz {

    private SocketClient socketClient;

    public Aclazz() {
        this.socketClient = SocketClient.getInstance();
    }

    public SocketClient getSocketClient() {
        return this.socketClient;
    }
}

3) Bclazz

package com.company.design.singleton;

public class Bclazz {
    private SocketClient socketClient;

    public Bclazz() {
        this.socketClient = SocketClient.getInstance();
    }

    public SocketClient getSocketClient() {
        return this.socketClient;
    }
}

4) Main

package com.company.design;

import com.company.design.singleton.Aclazz;
import com.company.design.singleton.Bclazz;
import com.company.design.singleton.SocketClient;

public class Main {

    public static void main(String[] args) {

        Aclazz aclazz = new Aclazz();
        Bclazz bclazz = new Bclazz();

        SocketClient aClient = aclazz.getSocketClient();
        SocketClient bClient = bclazz.getSocketClient();

        System.out.println("두 개의 객체가 동일한가?");
        System.out.println(aClient.equals(bClient));
    }
}

  • 싱글톤 패턴은 자바에서 배웠듯이 디자인 패턴중의 하나이고, 자기 자신을 객체로 갖기 위해서

    private SocketClient() {}
    public static SocketClient getInstance()

    라는 부분이 반드시 필요하다!

profile
혼자서 코딩 공부하는 전공생 초보 백엔드 개발자 / https://github.com/leejinseok0614

0개의 댓글