[英]Rust trait state
我將從Rust的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 ++中執行相同的操作。 我可以找到一些丑陋和不直觀的方法來解決此問題,但是有減少代碼的好方法嗎? 我的意思是,使其保持可伸縮性和可讀性。
有利於組合的另一種方法,如果需要的話,也可以從中更容易地DwarvenAngel
實現(例如, 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)
}
}
或者,您可以讓一個枚舉代表您的怪物類型,與AB的答案非常相似:
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)
}
}
}
您認為這樣的解決方案可以接受嗎?
trait Actor {
fn attack(&self);
}
enum MonsterId {
IndustrialRaverMonkey,
DwarvenAngel
}
struct Monster {
life: int,
strength: int
}
impl Monster {
fn new(id: MonsterId) -> Monster {
match id {
IndustrialRaverMonkey =>
Monster { life: 12, strength: 8 },
DwarvenAngel =>
Monster { life: 18, strength: 12 }
}
}
}
impl Actor for Monster {
fn attack(&self) {}
}
更新了一個更好的例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.