티스토리 뷰

JAVA/Design Pattern

싱글톤

tsgoing 2022. 1. 10. 20:52

싱글톤 패턴: 인스턴스 하나만 생성해야할 객체를 위한 패턴

인터페이스

개발 요구 사항: 개발 중에 시스템에서 스피커에 접근할 수 있는 클래스 생성

 

public class SystemSpeaker {
	static private SystemSpeaker instance = new SystemSpeaker();
    
    private SystemSpeak() {
    }
    
    public static SystemSpeaker getInstance() {
    	return instance;
    }
}

이렇게 하면 안된다

public class SystemSpeaker {
	static private SystemSpeaker instance;
    
    private SystemSpeak() {
    }
    
    public static SystemSpeaker getInstance() {
    	if (instance == null) {
        	// 시스템 스피커
        	instance = new SystemSpeaker();
        }
    	return instance;
    }
}

 

인스턴스의 존재 여부를 체크하기 위해서 null 체크

1) null이면 인스턴스를 할당

2) null이 아니면 인스턴스를 반환

 

public class SystemSpeaker {
	
    // 하나의 인스턴스만 접근하기 위해서 static으로
    
    static private SystemSpeaker instance;
    private ine volume;
    
    // 외부에서 생성함수를 호출하지 않기 위해서 private
    private SystemSpeak() {
    	volume = 5;
    }
    
    // getInstance를 받기 위해서 static으로 해줘야 함.
    public static SystemSpeaker getInstance() {
    	if (instance == null) {
			// 시스템 스피커
            instance = new SystemSpeaker();
			System.out.println("새로 생성");
            
        } else {
        	System.out.println("이미 생성");
        }
    	return instance;
    }
    
    public int getVolume() {
    	return volume;
    }
    
    public void setVolume(int volume) {
    	this.volume = volume;
    }
}

 

public class Main {
	public static void main(String[] args) {
    	SystemSpeaker speaker1 = SystemSpeaker.getInstance();
        SystemSpeaker speaker2 = SystemSpeaker.getInstance();
        
        //5, 5
        System.out.println(speaker1.getVolume());
        System.out.println(speaker2.getVolume());
        
        speaker2.setVolume(11);
        
        //11, 11
        System.out.println(speaker1.getVolume());
        System.out.println(speaker2.getVolume());
        
    }
}

<참고자료>


https://www.youtube.com/watch?v=5jgpu9-ywtY&list=PLsoscMhnRc7pPsRHmgN4M8tqUdWZzkpxY&index=5 

 

최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함