您好我正在尝试创建抽象类 Person 和两个子类 Student 和 Staff。Person 类也有一个由 Practical 类通知的观察者。但学生只会收到有关更改的问题编号和有关学生感觉良好因素的工作人员的通知。任何学生都可以随时标记该因素。我已经设法让观察者工作,但仅限于 Person 类。我知道我必须将其抽象化,然后创建 Staff 和 Student 类,但我无法理解它。任何帮助都会很棒。谢谢 这是代码:
namespace ConsoleApplication1
{
class Practical : IPractical //Practical class
{
private String QuestionNumber;// the state which observers are interested in.
private String Factor;
private ArrayList observers; // the collection of observers attached to this subject.
public Practical(String qnumber, String f)
{
QuestionNumber = qnumber;
Factor = f;
observers = new ArrayList();
}
public void AddObserver(IPerson o) { observers.Add(o); }
public void RemoveObserver(IPerson o) { observers.Remove(o); }
public void NotifyObserverQN()
{
foreach (IPerson o in observers) { o.Update(QuestionNumber); }
}
public void NotifyObserverFactor()
{
foreach (IPerson o in observers) { o.Update(Factor); }
}
public String QN
{
get { return QuestionNumber; }
set
{
QuestionNumber = value;
NotifyObserverQN(); //notify about new question
}
}
public String Fc
{
get { return Factor; }
set
{
Factor = value;
NotifyObserverFactor(); //notify about new ffctor
}
}
}
interface IPractical //IPractical interface
{
void AddObserver(IPerson o);
void RemoveObserver(IPerson o);
void NotifyObserverQN();
void NotifyObserverFactor();
}
class Person : IPerson
{
private string id;
public Person(string i) { id = i; }
public void Update(Object o) { Console.WriteLine(" {0} notified about {1} .", id, o.ToString()); }
}
interface IPerson //Observer interface
{
void Update(Object o);
}
class Observer
{
public static void Main()
{
Console.WriteLine("\n\nStart\n\n");
Practical practical = new Practical("Question", "Factor");
IPerson a, b, c;
a = new Person(" Student_1 ");
b = new Person(" Student_2 ");
c = new Person(" Staff_1 ");
practical.AddObserver(a);
practical.AddObserver(b);
practical.AddObserver(c);
practical.QN = "Question 1"; // all students notifie about Question 1
practical.Fc = "Feel-Good";
practical.QN = "Question 2"; // all students notifie about Question 2
practical.Fc = "Feel-Bad";
Console.WriteLine("\n\nEnd\n\n");
}
}
}