Не уверен, если это то, что вы ищете, но я бы этот:
// first some implementations
public class Sword : ISword {
public void Kill() { // imp }
public void Slice() { // imp }
}
public class Shuriken : IShuriken {
public void Kill() { // imp }
public void Pierce() { // imp }
}
// and I would change the Ninja class to
public class Ninja {
public ISword Sword { get; private set; }
public IShuriken Shuriken { get; private set; }
public Ninja(ISword sword, IShuriken shuriken) {
this.Sword = sword;
this.Shuriken = shuriken;
}
public void BrutalKill() {
Shuriken.Pierce();
Shuriken.Pierce();
Shuriken.Pierce();
// either weapon can kill
// so lets close the distance and use the sword
Sword.Kill();
}
public void HonorKill {
Sword.Slice();
}
}
// creating the class
// where Ioc.Resolve is specific to the container implementation
var ninja = new Ninja(IoC.Resolve<ISword>(), IoC.Resolve<IShuriken>());
Обновление I как комментарий Фила Сандлера, так быстро обновить, чтобы это отразить:
// a ninja interface
public interface INinja {
void BrutalKill();
void HonorKill();
}
// and then update the ninja class to
public Ninja : INinja {
...
}
// and have the ninja class created like this with the container
// resolving the dependencies:
var ninja = IoC.Resolve<INinja>();
Update Основываясь на обновление к первоначальному вопросу, я бы сказал:
public interface IWeapon {
void Attack();
void Kill();
}
public class Sword : ISword {
public void Attack() {
// implement as a slash
}
...
}
public class Shuriken : IShuriken {
public void Attack() {
// implement as a pierce
}
...
}
Идея заключается в том, что мы на самом деле не волнует, как Меч и Shuriken реализации атаки, до тех пор, ниндзя может использовать их для выполнения своего долга, когда его призывают. Убийство может быть каримым, как пожелает конкретный ниндек, пока работа выполняется в рамках указанного соглашения, в этом случае путем нападения.
// create the specific ninja
var swordNinja = new Ninja(IoC.Resolve<ISword>());
var shurikenNinja = new Ninja(IoC.Resolve<IShuriken>());
// with the ninja class updated to only have an IWeapon
// property that gets set in the constructor.
Какие IoC вы используете? –
Разве ваш ниндзя не нуждался бы в мече и инсурине? Я не понимаю, почему вы только что создали зависимость от IWeapon. –
@Phil Sandler: Я думаю о том, что ниндзя должен быть вооружен оружием ... если он хочет быть вооруженным мечом или сюрикеном ... должно быть решено позже ... не уверен, что я думаю правильно – Perpetualcoder