Skip to content

Commit dc83c9f

Browse files
committed
改进版的观察者模式
1 parent 9a0fb25 commit dc83c9f

3 files changed

Lines changed: 25 additions & 4 deletions

File tree

DesignPatterns/ObserverPattern/ObserverPattern/Country.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public CountryA(string countryName, Spy spy) : base(countryName, spy)
3131

3232
public override void Update()
3333
{
34-
Console.WriteLine(countryName+"得到情报"+spy.GetIntelligence()+"建交");
34+
Console.WriteLine(countryName+"得到情报"+spy.spyName+"的情报"+spy.GetIntelligence()+"建交");
3535
}
3636
}
3737

@@ -43,7 +43,7 @@ public CountryB(string countryName, Spy spy) : base(countryName, spy)
4343

4444
public override void Update()
4545
{
46-
Console.WriteLine(countryName+"得到情报"+spy.GetIntelligence()+"开战");
46+
Console.WriteLine(countryName + "得到情报" + spy.spyName + "的情报" + spy.GetIntelligence() + "建交");
4747
}
4848
}
4949
}

DesignPatterns/ObserverPattern/ObserverPattern/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class Program
1010
{
1111
static void Main(string[] args)
1212
{
13-
Spy spy = new Spy();
13+
Spy spy = new Spy007("007");
1414

1515
CountryA countryA = new CountryA("A",spy);
1616
CountryB countryB = new CountryB("B",spy);

DesignPatterns/ObserverPattern/ObserverPattern/Spy.cs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,16 @@
66

77
namespace ObserverPattern
88
{
9-
class Spy
9+
abstract class Spy
1010
{
1111
private List<Country> listener= new List<Country>();
1212
private string intelligence;
13+
public string spyName;
14+
15+
public Spy(string name)
16+
{
17+
this.spyName = name;
18+
}
1319

1420
/// <summary>
1521
/// 添加监听,进入国家
@@ -49,4 +55,19 @@ public string GetIntelligence()
4955
return this.intelligence;
5056
}
5157
}
58+
59+
60+
class Spy007 : Spy
61+
{
62+
public Spy007(string name) : base(name)
63+
{
64+
}
65+
}
66+
67+
class Mole : Spy
68+
{
69+
public Mole(string name) : base(name)
70+
{
71+
}
72+
}
5273
}

0 commit comments

Comments
 (0)