[설계 패턴 C#] 21. 감시자 패턴(Observer Pattern)
"본문 내용"
[Escort GoF의 디자인 패턴 C#] 21. 감시자 패턴(Observer Pattern)
[Escort GoF의 디자인 패턴 C#] 21. 감시자 패턴(Observer Pattern) 설계
[Escort GoF의 디자인 패턴 C#] 21. 감시자 패턴(Observer Pattern) 구현
▶ Subject.cs
using System.Collections.Generic;
namespace Observer
{
class Subject
{
List<IUpdate> observers = new List<IUpdate>();
public void AddObserver(IUpdate observer)
{
observers.Add(observer);
}
public void RemoveObserver(IUpdate observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach (IUpdate observer in observers)
{
observer.Update();
}
}
}
}
▶ Picture.cs
using System;
namespace Observer
{
class Picture:Subject
{
public string Name{ get; private set; }
public int Tone { get; private set; }
public int Brightness{ get; private set; }
public int Saturation{ get; private set; }
public Picture(string name,int tone,int brightness,int saturation)
{
Name = name;
Tone = tone;
Brightness = brightness;
Saturation = saturation;
}
public void Change(int tone,int brightness,int saturation)
{
Tone+=tone;
Brightness += brightness;
Saturation += saturation;
Notify();
}
public void View()
{
Console.WriteLine("사진 파일명:{0}",Name);
Console.WriteLine(" 색조:{0} 명도:{1} 채도:",Tone,Brightness,Saturation);
}
}
}
▶ IUpdate.cs
namespace Observer
{
interface IUpdate
{
void Update();
}
}
▶ ToneViewer.cs
using System;
namespace Observer
{
class ToneViewer:IUpdate
{
Picture picture = null;
public ToneViewer(Picture picture)
{
this.picture = picture;
}
public void Update()
{
Console.WriteLine("이름:{0} 색조:{1}", picture.Name, picture.Tone);
}
}
}
▶ BrightnessViewer.cs
using System;
namespace Observer
{
class BrightnessViewer:IUpdate
{
Picture picture;
public BrightnessViewer(Picture picture)
{
this.picture = picture;
}
public void Update()
{
Console.WriteLine("이름:{0} 명도:{1}", picture.Name, picture.Brightness);
}
}
}
▶ SaturationViewer.cs
using System;
namespace Observer
{
class SaturationViewer :IUpdate
{
Picture picture = null;
public SaturationViewer(Picture picture)
{
this.picture = picture;
}
public void Update()
{
Console.WriteLine("이름:{0} 채도:{1}", picture.Name, picture.Saturation);
}
}
}
▶ Program.cs
namespace Observer
{
class Program
{
static void Main(string[] args)
{
Picture picture = new Picture("제주도의 밤",100,100,100);
IUpdate[] observers = new IUpdate[3];
observers[0] = new ToneViewer(picture);
observers[1] = new BrightnessViewer(picture);
observers[2] = new SaturationViewer(picture);
picture.AddObserver(observers[0]);
picture.AddObserver(observers[1]);
picture.AddObserver(observers[2]);
picture.Change(3,10,5);
}
}
}
'.NET > 설계 패턴(C#)' 카테고리의 다른 글
[설계 패턴 C#] 23. 전략 패턴(Strategy Pattern) (0) | 2016.12.09 |
---|---|
[설계 패턴 C#] 22. 상태 패턴(State Pattern) (0) | 2016.12.09 |
[설계 패턴 C#] 20. 메멘토 패턴(Memento Pattern) (0) | 2016.12.08 |
[설계 패턴 C#] 19. 중재자 패턴(Mediator Pattern) (0) | 2016.12.08 |
[설계 패턴 C#] 18. 반복자 패턴(Iterator Pattern) (0) | 2016.12.07 |