Singleton Pattern

    Singleton Pattern 

    어떠한 클래스가 유일하게 1개만 존재할 때 사용

     

    서로 자원을 공유할 때 주로 사용

    Ex) 실물 세계 : 프린터

          프로그래밍 : TCP Socket 통신에서 서버와 연결된 connect 객체

     

    SocketClient.java

    package com.company.design.singleton;
    
    public class SocketClient {
        private static SocketClient socketClient = null;
    
        // default 생성자 private으로 막기
        // private SocketClient() {
        public SocketClient() {
    
        }
    
        // getInstance
        public static SocketClient getInstance() {
    
            // 자신이 가진 객체가 null 이면 새로 생성
            if(socketClient == null) {
                socketClient = new SocketClient();
            }
    
            // null 이 아닌 경우 return
            return socketClient;
        }
    
        public void connect() {
            System.out.println("connect");
        }
    }

     

    AClazz.java

    package com.company.design.singleton;
    
    public class AClazz {
    
        private SocketClient socketClient;
    
        public AClazz() {
            this.socketClient = new SocketClient();
           //this.socketClient = SocketClient.getInstance();
        }
    
        public SocketClient getSocketClient() {
            return this.socketClient;
        }
    }

     

    BClazz.java

    package com.company.design.singleton;
    
    public class BClazz {
    
        private SocketClient socketClient;
    
        public BClazz() {
            this.socketClient = new SocketClient();
            //this.socketClient = SocketClient.getInstance();
        }
    
        public SocketClient getSocketClient() {
            return this.socketClient;
        }
    }

     

    Main.java

    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));
        }
    }

     

    싱글톤 패턴 사용한 경우

    싱글톤 패턴 사용하지 않은 경우

    '기타' 카테고리의 다른 글

    웹 개발 개론 (REST API, URI 설계 패턴, HTTP Protocol)  (0) 2023.03.17
    디자인 패턴이란?  (0) 2023.03.17
    Process 용어  (0) 2022.08.02
    Eclipse 단축키 정리  (0) 2022.08.02

    댓글