본문으로 바로가기

참고)

싱글톤 패턴(Singleton pattern) 정의 간단한 코드 예제는  https://codehouse.tistory.com/9 에서 확인 있다. 반드시 해당 페이지에서 기본 정의에 대하여 숙지 하고 이후에 해당 예제 코드를 보기 바란다.

 

 

1. 블루투스(bluetooth) 신호 감지 및 등록 Singleton 예제

 

싱글톤패턴 예제로 블루투스의 신호를 감지하고, 기기를 등록 혹은 삭제하는 예제코드를 짜보기로 한다.

 

1-1 클래스 다이어그램(Class Diagram)

A - iMachine인터페이스와  laptop, phone, computer객체를 두어 블루투스 신호를 가진 기기를 구현한다.

B - BlueToothSingleton객체에서 모니터링 기기 삭제, 등록 역할을 수행한다. 해당 인스턴스는 lazyholder 클래스에서 한번만 생성하게된다.

 

 

1-2 예제상세

 

imachine.java

1
2
3
4
5
6
7
8
 
public interface iMachine {
    public void onSignal(); 
    public void offSignal(); 
    public boolean getStatus();
    public String getName();
}
 

 

 

computer.java

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
 
public class computer implements iMachine {
    private boolean signal;
    private String name = "computer";
 
    public computer() {
        this.signal = false;
    }
 
    @Override
    public void onSignal() {
        this.signal = true;
    }
 
    @Override
    public void offSignal() {
        this.signal = false;
    }
    
    public boolean getStatus() {
        return this.signal;
    }
    
    public String getName() {
        return name;
    }
 
}
 
 

 

 

 

laptop.java

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
 
public class laptop implements iMachine{
    private boolean signal;
    private String name = "laptop";
 
    public laptop() {
        this.signal = false;
    }
 
    @Override
    public void onSignal() {
        this.signal = true;
    }
 
    @Override
    public void offSignal() {
        this.signal = false;
    }
    
    public boolean getStatus() {
        return this.signal;
    }
    
    public String getName() {
        return name;
    }
}
 
 

 

 

 

phone.java

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
 
public class phone implements iMachine{
    private boolean signal;
    private String name = "phone";
    
    public phone() {
        this.signal = false;
    }
 
    @Override
    public void onSignal() {
        this.signal = true;
    }
 
    @Override
    public void offSignal() {
        this.signal = false;
    }
    
    public boolean getStatus() {
        return this.signal;
    }
    
    public String getName() {
        return name;
    }
}
 
 

 

 

 

BlueToothSingleton.java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package exSingleton;
 
 
public class BlueToothSingleton {
    private ArrayList<iMachine> onSignalmachine= new ArrayList<iMachine>();
    private ArrayList<iMachine> registMachine = new ArrayList<iMachine>();
 
    //생성자를 private으로 지정하여 client에서 객체생성을 금지한다.
    private BlueToothSingleton() {}
 
    //JVM에서 생성시에 해당 inner클래스를 이용하여 인스턴스를 생성시킨다.
    public static class lazyholder {
        private static final BlueToothSingleton singleton = new BlueToothSingleton();
    }
    
    //getInstance호출시 객체 return
    public static BlueToothSingleton getInstance() {
        return lazyholder.singleton;
    }
    
    public void startMonitoring(iMachine machine) {
        if(machine.getStatus()) {
            this.onSignalmachine.add(machine);
        }
    }
    
    public void stopMonitoring() {
        if(!this.onSignalmachine.isEmpty())
            this.onSignalmachine.clear();
    }
    
    public void printMonitorMachine() {
        for(int idx=0; idx < this.onSignalmachine.size(); idx++) {
            if(this.onSignalmachine.get(idx).getStatus())
                System.out.println("블루투스가 켜져있는 기계 : " + this.onSignalmachine.get(idx).getName());
        }
    }
    
    public void registerMachine(iMachine machine) {
        if(machine.getStatus()) {
            this.registMachine.add(machine);
        }else {
            System.out.println("해당장비를 등록 할 수 없습니다.");
        }
    }
    
 
    public void removeMachine(iMachine machine) {
        for(int idx = 0; idx < this.registMachine.size(); idx++) {
            if(this.registMachine.get(idx).getName() == machine.getName()) {
                this.registMachine.remove(idx);
                System.out.println(machine.getName() + " 이 등록 해제 되었습니다.");
            }
        }
    }
 
    public void printRegisterMachine() {
        for(int idx=0; idx < this.registMachine.size(); idx++) {
            if(this.registMachine.get(idx).getStatus())
                System.out.println("현재 등록된 기계 : " + this.registMachine.get(idx).getName());
        }
    }
    
}
 
 

 

 

 

BlueTooth.java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package exSingleton;
 
 
public class BlueTooth {
    public static void main(String[] args) {
 
        //첫번째 bluetooth 감지 시나리오
        iMachine computer = new computer();
        iMachine phone = new phone();
        iMachine laptop = new laptop();
        
        computer.onSignal();
        phone.offSignal();
        laptop.onSignal();
    
        //singleton 인스턴스 생성
        BlueToothSingleton singleton1 = BlueToothSingleton.getInstance();
        
        //모니터링에 machine 추가
        singleton1.startMonitoring(computer);
        singleton1.startMonitoring(phone);
        singleton1.startMonitoring(laptop);
        
        //감지된 machine 리스트 출력
        singleton1.printMonitorMachine();
    
        //machine 등록
        singleton1.registerMachine(computer);
        singleton1.registerMachine(laptop);
        
        //등록된 machine 리스트 출력
        singleton1.printRegisterMachine();
        
        //모니터링 해제
        singleton1.stopMonitoring();
    
        
        //phone을 onsignal로 교체
        phone.onSignal();
        
        //singleton 인스턴스 생성
        BlueToothSingleton singleton2 = BlueToothSingleton.getInstance();
        
        //모니터링에 machine추가
        singleton2.startMonitoring(computer);
        singleton2.startMonitoring(phone);
        singleton2.startMonitoring(laptop);
        
        //감지된 machine 리스트 출력
        singleton2.printMonitorMachine();
        
        //등록된 machine중 computer 삭제
        singleton2.removeMachine(computer);
        
        //phone machine 등록
        singleton2.registerMachine(phone);
        
        //등록된 machine 리스트 출력
        singleton2.printRegisterMachine();
        
        //모니터링 해제
        singleton2.stopMonitoring();
    }
 
}
 
 

 

 

 

결과)

블루투스가 켜져있는 기계 : computer
블루투스가 켜져있는 기계 : laptop

현재 등록된 기계 : computer
현재 등록된 기계 : laptop

블루투스가 켜져있는 기계 : computer
블루투스가 켜져있는 기계 : phone
블루투스가 켜져있는 기계 : laptop

computer 이 등록 해제 되었습니다.

현재 등록된 기계 : laptop
현재 등록된 기계 : phone

 

최초 BlueToothSingleton객체를 생성하고 기기를 등록하고 나서, 다시 새로운 BlueToothSingleton변수에 인스턴스를 생성하여도 기존에 등록된 기기 정보가 그대로 유지됨을 있다.