如何使用C#的策略模式? [英] How to use the Strategy Pattern with C#?
本文介绍了如何使用C#的策略模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我到目前为止有:
Here's what I have so far:
namespace Strategy
{
interface IWeaponBehavior
{
void UseWeapon();
}
}
namespace Strategy
{
class Knife : IWeaponBehavior
{
public void UseWeapon()
{
Console.WriteLine("You used the knife to slash the enemy! SLASH SLASH!");
}
}
}
namespace Strategy
{
class Pan : IWeaponBehavior
{
public void UseWeapon()
{
Console.WriteLine("You use the pan! 100% Adamantium power! BONG!");
}
}
}
现在超的.cs。怎么可能超实现weaponbehavior让孩子类可以更具体。
Now if I have a Character.cs superclass. how can that superclass implement a weaponbehavior so that children classes can be more specific.
namespace Strategy
{
class Character
{
public IWeaponBehavior weapon;
public Character(IWeaponBehavior specificWeapon)
{
weapon = specificWeapon;
}
}
}
namespace Strategy
{
class Thief : Character
{
}
}
我如何能实现这一点?我在什么实际的代码需要很困惑。
How can I implement this? I'm very confused on what the actual code needs to be.
我知道这可能会问太多,但如果你能编写实际的代码,所以我可以学习它,那将是非常好的你们的。我通过看代码学习。 :P。很多人可能会受益于这个问题。
I know this might be asking too much, but if you could write the actual code so I could study it, that would be very nice of you guys. I learn by seeing code. :P Many people could benefit from this question.
推荐答案
使用依赖注入类字符
?
public class Character
{
public Character(IWeaponBehavior weapon)
{
this.weapon = weapon;
}
public void Attack()
{
weapon.UseWeapon();
}
IWeaponBehavior weapon;
}
public class Princess: Character
{
public Princess() : base(new Pan()) { }
}
public class Thief: Character
{
public Thief() : base(new Knife()) { }
}
...
Princess p = new Princess();
Thief t = new Thief();
p.Attack(); // pan
t.Attack(); // knife
编辑的要求。
Edited as requested.
这篇关于如何使用C#的策略模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文