반응형

IObserver<T> interface와 IObservable<T> interface를 이용해 Observer Design Pattern을 구현해 보자.

 

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Observer
{
    class Program
    {
        static void Main(string[] args)
        {
            LocationTracker provider = new LocationTracker();
            // Provider 생성
 
            LocationReporter reporter1 = new LocationReporter("FixedGPS");
            reporter1.Subscribe(provider);
            // Observer(FixedGPS) 생성 및 Provider에 등록
 
            LocationReporter reporter2 = new LocationReporter("MobileGPS");
            reporter2.Subscribe(provider);
            // Observer(MobileGPS) 생성 및 Provider에 등록
 
            provider.TrackLocation(new Location(47.6456-122.1312));
            // FixedGPS: The current location is 47.6456, -122.1312
            // MobileGPS: The current location is 47.6456, -122.1312
 
            reporter1.Unsubscribe();
            // FixedGPS unsubscribed.
 
            provider.TrackLocation(new Location(47.6677-122.1199));
            // MobileGPS: The current location is 47.6677, -122.1199
 
            provider.TrackLocation(null);
            // MobileGPS: The location cannot be determined.
 
            provider.EndTransmission();
            // MobileGPS unsubscribed.
            // The Location Tracker has completed transmitting data to MobileGPS.
        }
    }
 
    // 위치 정보를 담고 있는 데이터 클래스
    public struct Location
    {
        double lat, lon;
 
        public Location(double latitude, double longitude)
        {
            lat = latitude;
            lon = longitude;
        }
 
        public double Latitude
        {
            get { return lat; }
        }
 
        public double Longitude
        {
            get { return lon; }
        }
    }
 
    // Provider 클래스 (등록된(subscribe) Observer에 Notification을 보낸다)
    // IObservable<out T> 인터페이스는 IDisposable Subscribe(IObserver<T> observer)를 구현해야 한다.
    public class LocationTracker : IObservable<Location>
    {
        private List<IObserver<Location>> observers;
 
        public LocationTracker()
        {
            observers = new List<IObserver<Location>>();
        }
 
        // Subscribe()는 LocationTracker 클래스에서 호출되지 않는다. LocationReporter.Subscribe()에서 호출
        public IDisposable Subscribe(IObserver<Location> observer)
        {
            if (!observers.Contains(observer))
                observers.Add(observer);
 
            return new Unsubscriber(observers, observer);
        }
 
        private class Unsubscriber : IDisposable
        {
            private List<IObserver<Location>> _observers;
            private IObserver<Location> _observer;
 
            public Unsubscriber(List<IObserver<Location>> observers, IObserver<Location> observer)
            {
                _observers = observers;
                _observer = observer;
            }
 
            public void Dispose()
            {
                if (_observer != null && _observers.Contains(_observer))
                    _observers.Remove(_observer);
            }
        }
 
        public void TrackLocation(Nullable<Location> loc)
        {
            // observers 순회하는 예 1
            foreach (IObserver<Location> observer in observers)
            {
                if (!loc.HasValue)
                    observer.OnError(new LocationUnknownException());
                else
                    observer.OnNext(loc.Value);
            }
        }
 
        public void EndTransmission()
        {
            // observers 순회하는 예 2
            foreach (IObserver<Location> observer in observers.ToArray())
                if (observers.Contains(observer))
                    observer.OnCompleted();
 
            observers.Clear();
        }
    }
 
    // LocationTracker.TrackLocation()에 Location 정보가 없을때 보내는 예외 클래스
    public class LocationUnknownException : Exception
    {
        internal LocationUnknownException() : base("The location cannot be determined.")
        { }
    }
 
    // Observer 클래스 (Provider에 등록(subscribe)하고 Notification을 받는다)
    // IObserver<in T> 인터페이스는 아래 3개의 매소드를 구현해야 한다.
    // void OnCompleted(), void OnError(Exception error), void OnNext(T value);
    public class LocationReporter : IObserver<Location>
    {
        private IDisposable unsubscriber;
        private string instName;
 
        public LocationReporter(string name)
        {
            instName = name;
        }
 
        public string Name
        { get { return instName; } }
 
        public virtual void Subscribe(IObservable<Location> provider)
        {
            if (provider != null)
                unsubscriber = provider.Subscribe(this);
        }
 
        public virtual void OnCompleted()
        {
            Unsubscribe();
            Console.WriteLine("The Location Tracker has completed transmitting data to {0}.", Name);
        }
 
        public virtual void OnError(Exception e)
        {
            Console.WriteLine("{0}: {1}", Name, e.Message);
        }
 
        public virtual void OnNext(Location value)
        {
            Console.WriteLine("{2}: The current location is {0}, {1}", value.Latitude, value.Longitude, Name);
        }
 
        public virtual void Unsubscribe()
        {
            unsubscriber.Dispose();
            Console.WriteLine("{0} unsubscribed.", Name);
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

위치정보 Notification이 잘 전달된다.

 

※참고

The IObserver<T> and IObservable<T> interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern.

 

반응형
Posted by J-sean
:
반응형

 

2022.01.06 - [C#] - C# AudioSwitcher System Audio/Sound Volume Control - 시스템 오디오/사운드 볼륨 컨트롤 1

의 소스를 수정해 Observer를 등록하고 VolumeChanged Notification을 받아 지정된 볼륨 이상 변경 하지 못 하도록 해 보자.

 

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
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Runtime.InteropServices;
using AudioSwitcher.AudioApi.CoreAudio;
using AudioSwitcher.AudioApi;
 
namespace ConsoleApp1
{
    class Program
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();
 
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
 
        static int maxVol;
 
        static void Main(string[] args)
        {
            const int SW_HIDE = 0// 창 숨기기
            const int SW_SHOW = 1// 창 보이기
 
            IntPtr handle = GetConsoleWindow();
            //ShowWindow(handle, SW_HIDE);            
 
            CoreAudioDevice defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
            Console.WriteLine($"Initial Volume: {defaultPlaybackDevice.Volume}");
 
            IObserver<DeviceVolumeChangedArgs> volumeChangeObserver = new VolumeChangeObserver();
            IDisposable subscriber = defaultPlaybackDevice.VolumeChanged.Subscribe(volumeChangeObserver);
 
            //subscriber.Dispose(); // 볼륨 제한 종료
 
            if (args.Length > 0)
            {
                maxVol = int.Parse(args[0]);
            }
            else
            {
                maxVol = 30;
            }
 
            defaultPlaybackDevice.Volume = maxVol; // 허용 최고 볼륨으로 초기화
 
            while (true)
            {
                System.Threading.Thread.Sleep(10000); // 10초 지연
            }
        }
 
        public class VolumeChangeObserver : IObserver<DeviceVolumeChangedArgs>
        {
            public virtual void OnCompleted()
            {
                Console.WriteLine("Completed.");
            }
 
            public virtual void OnError(Exception e)
            {
                Console.WriteLine(e.Message);
            }
 
            public virtual void OnNext(DeviceVolumeChangedArgs args)
            {
                if (args.Volume > maxVol)
                {
                    Console.WriteLine($"Volume limit: {maxVol}");
                    args.Device.Volume = maxVol; // args.Volume = read only
                }
                else
                {
                    Console.WriteLine($"Current volume: {args.Volume}");
                }
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

옵션 없이 실행하면 볼륨을 30 이상 올릴 수 없다.

※ 참고

2022.01.08 - [C#] - C# Observer Design Pattern with The IObserver and IObservable interfaces

2023.10.26 - [Python] - Python Core Audio Windows Library 파이썬 코어 오디오 라이브러리

2023.10.28 - [C#] - C# Sound Meter 사운드 미터

 

반응형
Posted by J-sean
: