gpt4 book ai didi

c# - 如何依赖注入(inject)类/类型?

转载 作者:行者123 更新时间:2023-11-30 15:10:05 25 4
gpt4 key购买 nike

我正在努力解决一个设计问题,我不希望我的代码因为糟糕的解决方案而变得一团糟。我不会给出一个糟糕的类比,而是会解释我的确切案例。

我正在尝试编写 Wii Play Tanks 的克隆,但在设计 Tank 类时遇到了问题。 Tank 本身是唯一的此类,它的部分使用依赖注入(inject)。现在的两个部分是 TankAITankWeapon。 AI 处理关于移动和射击的决定,武器描述武器的行为方式 - 它发射什么射弹,发射频率等。我有一个工厂类,它以不同的组合 build 坦克。

我的射弹类是在一个抽象的 Projectile 类下设置的。每个子类描述弹丸的型号、弹跳次数、速度等。

我遇到的问题是,每个 TankWeapon 子类都在它们构造新射弹的区域周围复制大量代码,因为它们各自构造一个不同的类。我想将这段代码移到基类中,但我必须以某种方式注入(inject)武器需要构建的射弹类本身。我知道我确实可以在构建时将一个类传递给基础,但感觉这是错误的方法。

当我们这样做时,我遇到了另一个设计问题:如何让我的 AI 类也知道射弹类?他们的决定将取决于被发射的射弹的特性,例如它们可以从墙上弹回多少次。注入(inject)时,AI 和 Weapon 类都被赋予了对父 Tank 的引用。

编辑:

看来我的原始问题有点令人困惑,所以我将发布代码。我已经为我的坦克设置了 DI。

public class Tank : ISolidObject
{
public TankAI AISystem { get; private set; }
public TankWeapon Weapon { get; private set; }

public Tank(TankAI aiSystem, TankWeapon weapon)
{
this.AISystem = aiSystem;
this.AISystem.Tank = this;

this.Weapon = weapon;
this.Weapon.Tank = this;
}
}

public abstract class TankAI
{
public Tank Tank { get; set; }

public abstract void Think();
}

// TankAI implementations aren't important here

public abstract class TankWeapon
{
protected int maxShotsOnScreen, shotsOnScreen;

public Tank Tank { get; set; }

public virtual void Shoot()
{
shotsOnScreen++;

// I really want to put the projectile construction code in here
}
}

public class BulletWeapon : TankWeapon
{
public BulletWeapon()
{
this.maxShotsOnScreen = 5;
this.turnSpeed = 1;
}

public override void Shoot()
{
// here's my problem. Every weapon class duplicates this, because I can't put the projectile construction in the base weapon class.
if (shotsOnScreen >= maxShotsOnScreen) return;

base.Shoot();

// just create it, it will take care of the rest
double bx = Tank.X - Math.Sin(Tank.AngleTurret * Math.PI / 180.0);
double by = Tank.Y + Math.Cos(Tank.AngleTurret * Math.PI / 180.0);
// note that projectiles subscribe themselves to the game entity handler, so don't have to store it myself.

// this weapon creates bullets. A different weapon might create rockets. How would the base class know which? Is there any way I can prevent this code from being duplicated?
new Bullet(bx, by, Tank.AngleTurret).Death += ShotDeath;
}

private void ShotDeath(Projectile p)
{
p.Death -= ShotDeath;
shotsOnScreen--;
}
}

最佳答案

对于第一个问题,听起来您需要一个ProjectileFactory它看起来像

// somewhere in tank weapon's Fire method or whatever
Projectile p = projectileFactory.Create( myProjectile.GetType() );

对于第二个问题,让 AI 要求注入(inject) ProjectileType

public Tank( TankAi ai, TankWeapon w) // ...
public TankWeapon( Tank t, Projectile p ) // ...
public TankAi( Tank t, Projectile p ) // ...
public TankAi( Tank t, Type projectileType ) // ...

问你一个问题...为什么武器和 ai 会引用坦克?

关于c# - 如何依赖注入(inject)类/类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3588592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com