在不使用继承的情况下重用类似的构造函数



这是MonoGame 3.8.1和。net 6的代码。

public interface IEntity
{
int Size { get; }
Vector2 Position { get; }
}
public class Player : IEntity
{
public int Size { get; } = 32;
public Vector2 Position { get; private set; }
public Player(Scene scene)
{
var spawnOffset = new Vector2(0, -3);
Position = new Vector2(
spawnOffset.X * scene.TileSize + scene.Room.Center.x - Size / 2,
spawnOffset.Y * scene.TileSize + scene.Room.Center.y - Size / 2);
}
}
public class Enemy : IEntity
{
public int Size { get; } = 32;
public Vector2 Position { get; private set; }
public Enemy(Scene scene)
{
var spawnOffset = new Vector2(0, 0);

Position = new Vector2(
spawnOffset.X * scene.TileSize + scene.Room.Center.x - Size / 2,
spawnOffset.Y * scene.TileSize + scene.Room.Center.y - Size / 2);
}
}

不使用继承,我希望实现IEntity的每个类都能够重用Position分配的计算。两个构造函数的唯一区别是spawnOffset值。

最简单的方法是什么?

通常-我会调用基类构造函数,但这里我试图在没有基类的情况下这样做。

看起来您遵循了" prefer composition than inheritance ";-这确实是一个有效的方法,只需通过提取"位置"来完成它。功能放到单独的类中:


class EntityPosition
{
public Vector2 Position { get; private set; }
public EntityPosition (Scene scene, Vector2 spawnOffset, int size)
{
Position = new Vector2(
spawnOffset.X * scene.TileSize + scene.Room.Center.x - size / 2,
spawnOffset.Y * scene.TileSize + scene.Room.Center.y - size / 2);
}
// add other shared methods for position updates here as necessary
}
public class Player : IEntity
{
EntityPosition position;
public int Size { get; } = 32;
public Vector2 Position => position.Position;
public Player(Scene scene)
{
var spawnOffset = new Vector2(0, -3);
position = EntityPosition(scene, spawnOffset, Size);
}
}

相关内容

最新更新