角色:两种类型的角色(Person1,Person1)
武器:两种类型的武器(Weapon1,Weapon2)
武器类:
两个抽象类进行交互。(角色抽象类和武器抽象类交互)
和中介者模式的却别是,交互类为抽象类了,而中介者是子类之间的交互。
下面例子说明:人物使用的武器。
abstract class IPerson
{
protected IWeapon weapon;
public IPerson(IWeapon weapon)
{
this.weapon = weapon;
}
public abstract void Use();
}
abstract class IWeapon
{
public abstract void UseWeapon();
}
class Person1:IPerson
{
public Person1(IWeapon weapon):base(weapon)
{
}
public override void Use()
{
weapon.UseWeapon();
}
}
class Person2:IPerson
{
public Person2(IWeapon weapon) : base(weapon)
{
}
public override void Use()
{
weapon.UseWeapon();
}
}
class Weapon1:IWeapon
{
public override void UseWeapon()
{
Console.WriteLine("使用了武器1");
}
}
class Weapon2:IWeapon
{
public override void UseWeapon()
{
Console.WriteLine("使用了武器2");
}
}
static void Main(string[] args)
{
IPerson p1=new Person1(new Weapon1());
IPerson p2=new Person2(new Weapon2());
p1.Use();
p2.Use();
Console.ReadKey();
}