我将从这个来自Rust for Rubyist的“Monster”代码开始:
trait Monster {
fn attack(&self);
fn new() -> Self;
}
struct IndustrialRaverMonkey {
life: int,
strength: int,
charisma: int,
weapon: int,
}
struct DwarvenAngel {
life: int,
strength: int,
charisma: int,
weapon: int,
} ...
impl Monster for IndustrialRaverMonkey { ...
impl Monster for DwarvenAngel { ...
我担心代码重复的问题。在Java中,我会创建一个定义attack
方法的接口和一个带有所有参数(life
、strength
、charisma
、weapon
)的基类。在C++中,我会使用抽象类来实现同样的功能。
我可以找到一些丑陋和不直观的方法来解决这个问题,但是否有一种好的方法来减少代码?我的意思是,保持可扩展性和可读性。
~Characteristics
而不是简单的Characteristics
?(后者更推荐,很少有必要使用~
来堆分配(小型)结构体。) - undefined