例子
打牌(斗地主规则) 初始钱50 赢牌对面扣钱 地主赢扣20(地主40块) 农民赢扣20(农民一人10块)
public abstract class AbsMediator
{
public abstract void Register(Person obj);
/// <summary>
/// 赢牌
/// </summary>
/// <param name="obj"></param>
public abstract void HuCard(Person obj);
}
public abstract class Person
{
protected AbsMediator AbsMediator { get; set; }
public Person(string name, PersonType personType)
{
Name = name;
PersonType = personType;
Money = 100;
}
public void SetMediator(AbsMediator mediator)
{
AbsMediator = mediator;
}
public string Name { get; }
public PersonType PersonType { get; }
public int Money { get; set; }
public void HuCard()
{
AbsMediator.HuCard(this);
}
public abstract void ReceiveHuCard(Person person);
protected void AddQian(Person huPerson)
{
if (huPerson.PersonType == PersonType)
{
if (PersonType == PersonType.农民)
{
Money += 10;
}
else if (PersonType == PersonType.地主)
{
Money += 40;
}
}
}
protected void KouQian(Person huPerson)
{
if (huPerson.PersonType == PersonType.农民)
{
Money -= 20;
}
else if (huPerson.PersonType == PersonType.地主)
{
Money -= 20;
}
}
}
public enum PersonType
{
地主 = 0,
农民 = 1
}
public class NoMingPerson : Person
{
public NoMingPerson(string name) : base(name, PersonType.农民)
{
}
public override void ReceiveHuCard(Person person)
{
AddQian(person);
if (person.PersonType != PersonType.农民)
{
KouQian(person);
Console.WriteLine("地主赢啦,农民扣钱------还剩" + Money + this.Name);
}
}
}
public class DizhuPerson : Person
{
public DizhuPerson(string name) : base(name, PersonType.地主)
{
}
public override void ReceiveHuCard(Person person)
{
AddQian(person);
if (person.PersonType != PersonType.地主)
{
KouQian(person);
Console.WriteLine("农民赢啦,地主扣钱------还剩" + Money + this.Name);
}
}
}
public class DouDiZhuMediator : AbsMediator
{
private List<Person> colleagues = new List<Person>();
public override void Register(Person obj)
{
if (!this.colleagues.Contains(obj))
{
this.colleagues.Add(obj);
obj.SetMediator(this);
}
}
public override void HuCard(Person obj)
{
foreach (var item in this.colleagues)
{
item.ReceiveHuCard(obj);
}
}
}
class Program
{
static void Main(string[] args)
{
DizhuTest();
// NongmingTest();
}
private static void NongmingTest()
{
var doudizhu = new DouDiZhuMediator();
var dizhu = new DizhuPerson("地主");
var nongminga = new NoMingPerson("A农民");
var nongmingb = new NoMingPerson("B农民");
doudizhu.Register(dizhu);
doudizhu.Register(nongminga);
doudizhu.Register(nongmingb);
nongminga.HuCard();
Console.WriteLine(nongminga.Money + "," + nongmingb.Money);
}
private static void DizhuTest()
{
var doudizhu = new DouDiZhuMediator();
var dizhu = new DizhuPerson("地主");
var nongminga = new NoMingPerson("A农民");
var nongmingb = new NoMingPerson("B农民");
doudizhu.Register(dizhu);
doudizhu.Register(nongminga);
doudizhu.Register(nongmingb);
dizhu.HuCard();
Console.WriteLine(dizhu.Money);
}
}