Singleton pattern

This commit is contained in:
kim
2021-01-09 16:10:06 +09:00
parent 054954380b
commit 9c2547019e
3 changed files with 63 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
package Singleton;
public class Main {
public static void main(String[] args) {
SystemSpeaker speaker = SystemSpeaker.getInstance();
SystemSpeaker speaker2 = SystemSpeaker.getInstance();
System.out.println(speaker.getVolume());
System.out.println(speaker2.getVolume());
speaker.setVolume(11);
System.out.println(speaker.getVolume());
System.out.println(speaker2.getVolume());
speaker2.setVolume(22);
System.out.println(speaker.getVolume());
System.out.println(speaker2.getVolume());
}
}

View File

@@ -0,0 +1,12 @@
Singleton Pattern
하나의 인스턴스만 생성하여 사용
- 객체 : 속성과 기능을 갖춘 것
- 클래스 : 속성과 기능을 정의한 것
- 인스턴스 : 속성과 기능을 가진 것 중 실제 하는 것
요구사항
- 스피커에 접근할 수 있는 클래스 생성
추가
- 인스턴스를 호출할 때 로그를 찍어주는 소스 추가

View File

@@ -0,0 +1,30 @@
package Singleton;
public class SystemSpeaker {
static private SystemSpeaker instance;
private int volume;
private SystemSpeaker() {
volume = 5;
}
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;
}
}