角色:兩種類型的角色(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();
}