Singleton pattern
This commit is contained in:
21
design-pattern/src/Singleton/Main.java
Normal file
21
design-pattern/src/Singleton/Main.java
Normal 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());
|
||||
}
|
||||
}
|
||||
12
design-pattern/src/Singleton/Singleton
Normal file
12
design-pattern/src/Singleton/Singleton
Normal file
@@ -0,0 +1,12 @@
|
||||
Singleton Pattern
|
||||
|
||||
하나의 인스턴스만 생성하여 사용
|
||||
- 객체 : 속성과 기능을 갖춘 것
|
||||
- 클래스 : 속성과 기능을 정의한 것
|
||||
- 인스턴스 : 속성과 기능을 가진 것 중 실제 하는 것
|
||||
|
||||
요구사항
|
||||
- 스피커에 접근할 수 있는 클래스 생성
|
||||
|
||||
추가
|
||||
- 인스턴스를 호출할 때 로그를 찍어주는 소스 추가
|
||||
30
design-pattern/src/Singleton/SystemSpeaker.java
Normal file
30
design-pattern/src/Singleton/SystemSpeaker.java
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user