C\#디자인 모델 의 Observer 관찰자 모델 로 뉴턴 어린이 신발 성적 문 제 를 해결 하 는 예시
이론 적 정의
관찰자 모델 은 한 쌍 의 다 중 관 계 를 묘사 했다.어떤 대상 의 상태 가 바 뀌 면 다른 대상 은 변 경 된 통 지 를 받는다.상응하는 반응 을 보이다.
예 를 들다
수요 설명:뉴턴 학생 들 의 기말고사 성적(Score)이 나 왔 습 니 다.각 과 선생님 들 은 자신의 학생 성적 상황 을 알 고 싶 어 합 니 다!
국어 선생님(TeacherChinese)관심 밖 에 없어 요. 뉴턴 의 국어 성적.
영어 선생님(TeacherEnglish)관심 밖 에 없어 요. 뉴턴 의 영어 성적.
수학 선생님(TeacherMathematics)관심 밖 에 없어 요. 뉴턴 의 수학(Mathematics)성적.
담임 선생님 관심 갖 고 싶 어 요. 뉴턴 의 각 과목 성적 과 총 성적(Total Score).
성적 이 나 온 후 각 과목 의 선생님 들 은 모두 통 지 를 받 았 다(Notify).
구체 적 인 코딩
1.학생 정보 클래스 를 추가 합 니 다.Name 속성 만 있 습 니 다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Com.Design.Gof.Observer
{
/// <summary>
///
/// </summary>
public class Student
{
/// <summary>
///
/// </summary>
public string Name { get; set; }
}
}
2.성적표(점수)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Com.Design.Gof.Observer
{
public delegate void NotifyEventHandler(Score score);
public class Score
{
public Score() { }
//
public NotifyEventHandler NotifyEvent=null;
/// <summary>
///
/// </summary>
public void Notify() {
OnNotifyChange();
}
/// <summary>
///
/// </summary>
private void OnNotifyChange() {
if (NotifyEvent != null) {
NotifyEvent(this);
}
}
/// <summary>
///
/// </summary>
public float Mathematics { get; set; }
/// <summary>
///
/// </summary>
public float English { get; set; }
/// <summary>
///
/// </summary>
public float Chinese { get; set; }
/// <summary>
///
/// </summary>
public float TotalScore {
get {
return Mathematics+English+Chinese;
}
}
/// <summary>
///
/// </summary>
public Student student { get; set; }
}
}
3.국어 선생님
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Com.Design.Gof.Observer
{
/// <summary>
///
/// </summary>
public class TeacherChinese
{
public void Receive(Score score) {
Console.WriteLine(" , "+score.student.Name+" :"+score.Chinese+" ");
}
}
}
4.영어 선생님
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Com.Design.Gof.Observer
{
/// <summary>
///
/// </summary>
public class TeacherEnglish
{
public void Receive(Score score) {
Console.WriteLine(" , " + score.student.Name + " :" + score.English + " ");
}
}
}
5.수학 선생님
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Com.Design.Gof.Observer
{
/// <summary>
///
/// </summary>
public class TeacherMathematics
{
public void Receive(Score score) {
Console.WriteLine(" , " + score.student.Name + " :" + score.Mathematics + " ");
}
}
}
6.담임 선생님
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Com.Design.Gof.Observer
{
/// <summary>
///
/// </summary>
public class TeacherTeacherHead
{
public void Receive(Score score) {
string name=score.student.Name;
Console.WriteLine(" , " + name + " ");
Console.WriteLine(name + " : " + score.Chinese + " ");
Console.WriteLine(name + " : " + score.English + " ");
Console.WriteLine(name + " : " + score.Mathematics + " ");
Console.WriteLine(name + " : " + score.TotalScore + " ");
}
}
}
7.다음은 주 함수 호출
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com.Design.Gof.Observer;
namespace Com.Design.Gof.Test
{
class Program
{
static void Main(string[] args)
{
#region Observer
/* */
Score score = new Score {
Chinese = 60,
Mathematics = 100,
English = 90,
student = new Student { Name = " " }
};
TeacherChinese teacherChinese = new TeacherChinese(); //
TeacherEnglish teacherEnglish = new TeacherEnglish();//
TeacherMathematics teacherMathematics = new TeacherMathematics();//
TeacherTeacherHead teacherTeacherHead = new TeacherTeacherHead();//
// , 。
score.NotifyEvent += new NotifyEventHandler(teacherChinese.Receive);
score.NotifyEvent += new NotifyEventHandler(teacherEnglish.Receive);
score.NotifyEvent += new NotifyEventHandler(teacherMathematics.Receive);
score.NotifyEvent += new NotifyEventHandler(teacherTeacherHead.Receive);
// ,
score.Notify();
#endregion
Console.ReadKey();
}
}
}
8.실행 결과9.총화
C\#언어 가 제공 하 는 이벤트 와 알림 을 사용 하면 관찰자 모드 를 더욱 우아 하 게 실현 할 수 있 습 니 다.사건 의+=조작 은 정말 사람 을 So happy 하 게 한다.
첨부:전체 인 스 턴 스 코드 는 여 기 를 클릭 하 십시오본 사이트 다운로드
더 많은 C\#관련 내용 은 본 사이트 의 주 제 를 볼 수 있다.,,,,,,
본 고 에서 말 한 것 이 여러분 의 C\#프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.