2013-04-09 75 views
2

D语言有'别名...'。 Go嵌入了字段。在下面的代码中,Dart是否有办法到达啮齿动物的大肠,而不经过内脏?理想情况下,某种暴露内部组合的方法,不需要在每个动物中使用一些常见的内部组件创建转发呼叫?自动呼叫转移 - 访问啮齿动物的大肠

import 'dart:io'; 

class Stomach { 
    work() { print("stomach"); } 
} 
class LargeIntestine { 
    work() { print("large intestine"); } 
} 
class SmallIntestine { 
    work() { print("small intestine"); } 
} 

class Guts { 
    Stomach stomach = new Stomach(); 
    LargeIntestine largeIntestine = new LargeIntestine(); 
    SmallIntestine smallIntestine = new SmallIntestine(); 
    work() { 
    stomach.work(); 
    largeIntestine.work(); 
    smallIntestine.work(); 
    } 
} 

class Rodent { 
    Guts guts = new Guts(); 
    work() => guts.work(); 
} 

main() { 
    Rodent rodent = new Rodent(); 
    rodent.guts.largeIntestine; 
    rodent.work(); 
} 

回答

2

我很欣赏你在...生物学的兴趣,并很高兴地说,你要寻找的结构可能是get关键字。

参见:http://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#classes-getters-and-setters

class Rodent { 
    Guts guts = new Guts(); 
    work() => guts.work(); 

    // Getter for the Rodent's large intestine. 
    LargeIntestine get largeIntestine => guts.largeIntestine; 
} 

main() { 
    Rodent rodent = new Rodent(); 

    // Use the getter. 
    rodent.largeIntestine; 
    rodent.work(); 

    rodent.awake(); 
    rodent.recognizeMaster(); 
    if (rodent.self.awareness && rodent.self.isMonster) { 
    rodent.turn.on(rodent.master); 
    print("Oh. Oh, no! NoOooOO! Argghhhhhh..."); 
    rodent.largeIntestine.work(); 
    } 
} 

或者,如果你正在寻找保存编写工作,你可以有一个超类或接口或混入(取决于你想要做什么),有

class Animal { 
    LargeIntestine largeIntestine = new LargeIntestine(); 
    ... 
} 

class Rodent extends Animal { ... } 

class Rodent extends Object with Animal { ... } 
:你要找的属性

请参阅:http://www.dartlang.org/articles/mixins/

+0

谢谢。实际上,我正在寻找比为每个动物的每个器官宣布“获得”更少的工作。例如,用D你可以在Rodent中“混淆这个胆量”,然后你可以直接从Rodent中使用胆量成员。因此,这是一个玩具的例子,但假设将有30只动物,我不想要30 * 3的复制/粘贴获得者(即没有复制/粘贴转发)。我还没有在Dart中使用mixins,所以也许这有一个潜在的解决方案? – user1338952 2013-04-09 19:51:30