2014-04-08 40 views
0

我会用这个怪物“怪物”代码Rust for Rubyist开始:锈病性状状态

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++中做同样的事情。 我可以找到一些丑陋而不直观的方法来解决这个问题,但有没有减少代码的好方法?我的意思是,保持它的可扩展性和可读性。

回答

0

你会认为这是一个可接受的解决方案吗?

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) {} 
} 

更新了一个更好的例子。

2

另一种方法,这有利于组成,并从其中如果需要的话更容易发散的实现(例如,CharacteristicsDwarvenAngel需要额外的字段):

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) 
     } 
    } 
} 
+0

出于兴趣,为什么'〜特征'在结构中,而不是'特征'? (后者推荐,很少需要用'〜'来分配(小)结构。) – huon

+0

@dbaupp实际上,我仍然是一个noob。你是对的,那是一个小结构。我会修改我的答案。欢迎任何其他建议。 –

+0

据我所知,我必须实施派遣自己......这很有趣,我是rustnoob,并认为还有一些其他的机制。 –