我将从 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
方法和基类的接口(interface),其中包含所有参数(life
、strength
、charisma
, 武器
)。我将在 C++ 中使用抽象类做同样的事情。
我可以找到一些丑陋和不直观的方法来解决这个问题,但是有减少代码的好方法吗?我的意思是,保持它的可扩展性和可读性。
最佳答案
另一种方法,它有利于组合,并且在需要时更容易从中分离实现(例如,DwarvenAngel
的Characteristics
需要一个额外的字段):
trait Monster {
fn attack(&self);
}
struct Characteristics {
life: int,
strength: int,
charisma: int,
weapon: int,
}
struct IndustrialRaverMonkey {
characteristics: Characteristics
}
struct DwarvenAngel {
characteristics: Characteristics
}
fn same_attack(c: Characteristics) {
fail!("not implemented")
}
impl Monster for IndustrialRaverMonkey {
fn attack(&self) {
same_attack(self.characteristics)
}
}
impl Monster for DwarvenAngel {
fn attack(&self) {
same_attack(self.characteristics)
}
}
或者,您可以用一个枚举来表示您的怪物类型,这与 A.B. 的回答非常相似:
trait Monster {
fn attack(&self);
}
struct Characteristics {
life: int,
strength: int,
charisma: int,
weapon: int,
}
enum Monsters {
IndustrialRaverMonkey(Characteristics),
DwarvenAngel(Characteristics),
}
fn same_attack(_: &Characteristics) {
fail!("not implemented")
}
impl Monster for Monsters {
fn attack(&self) {
match *self {
IndustrialRaverMonkey(ref c) => same_attack(c),
DwarvenAngel(ref c) => same_attack(c)
}
}
}
关于struct - Rust 特征状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22935449/