首页 新闻 会员 周边

能否做得更好

0
悬赏园豆:20 [已解决问题] 解决于 2008-12-29 12:03
<P>我有一个动物类,它只有一个“叫三声”的方法,然后猫类与狗类都从它继承而来。现在我想猫应该“喵喵喵”叫,狗应该“汪汪汪”叫,我是用如下代码实现,但,有没有更好的方法,或是一些能用得上设计模式的方法(我是为设计模式而设计模式)。</P> <P>using System;<BR>class animal<BR>{<BR>&nbsp;protected string m_shout="";</P> <P>&nbsp;public void shout()<BR>&nbsp;{<BR>&nbsp; for (var i=0; i&lt;3; i++)<BR>&nbsp;&nbsp; Console.Write(m_shout);<BR>&nbsp; Console.Write("\n");<BR>&nbsp;}<BR>}</P> <P>class cat : animal<BR>{<BR>&nbsp;public cat()<BR>&nbsp;{<BR>&nbsp; m_shout="喵";<BR>&nbsp;}<BR>}</P> <P>class dog : animal<BR>{<BR>&nbsp;public dog()<BR>&nbsp;{<BR>&nbsp; m_shout="汪";<BR>&nbsp;}<BR>}</P> <P>class main<BR>{<BR>&nbsp; static void Main()<BR>&nbsp; {<BR>&nbsp;&nbsp;&nbsp; cat cat1=new cat();<BR>&nbsp;&nbsp;&nbsp; cat1.shout();</P> <P>&nbsp;&nbsp;&nbsp; dog dog1=new dog();<BR>&nbsp;&nbsp;&nbsp; dog1.shout();<BR>&nbsp; }<BR>}&nbsp;</P> <P>谢谢!</P>
yzx99的主页 yzx99 | 初学一级 | 园豆:137
提问于:2008-08-14 16:51
< >
分享
最佳答案
0
文字太多,写到下面这篇里面了 http://www.cnblogs.com/eaglet/archive/2008/08/15/1268392.html
eaglet | 专家六级 |园豆:17139 | 2008-08-15 09:40
其他回答(9)
0
个人感觉,应该是Refactoring to patterns,不一定非得在一开始就进行完美设计.
水言木 | 园豆:586 (小虾三级) | 2008-08-14 16:55
0
叫是一种行为,我感觉应该在animal中定义shout的抽象方法,然后在具体动物中重写这个方法。
玉开 | 园豆:8822 (大侠五级) | 2008-08-14 17:01
0
同意玉开的想法,在animal中定义shout的抽象方法,在具体的动物中实现相应的叫法
AndyFish | 园豆:1575 (小虾三级) | 2008-08-14 18:11
0
public abstract class Animal { public string Execute() { Console.WriteLine(Shout()); } protected abstract string Shout(); } public class Dog : Animal { protected override string Shout() { return "狗在叫...."; } } public class Cat : Animal { protected override string Shout() { return "猫在叫....."; } } =============================== 调用: Animal animal = new Cat(); Animal animal1 = new Dog(); animal.Execute(); animal1.Execute();
咸蛋超人 | 园豆:485 (菜鸟二级) | 2008-08-14 18:20
0
可以把叫这个行为分离成一个对象 不过在这种需求里没有什么用就是了=。=
小眼睛老鼠 | 园豆:2731 (老鸟四级) | 2008-08-14 18:29
0
supper class:virtual sub class:override
lexus | 园豆:0 (初学一级) | 2008-08-14 20:13
0
比较赞同 咸蛋超人 的方法,这样可以做到依赖接口编程,上层只用管“是个Animal就会Shout()”,而不用管“到底是哪种Animal”。
JimLiu | 园豆:300 (菜鸟二级) | 2008-08-15 01:51
0
http://www.cnblogs.com/justinw/archive/2007/02/06/641414.html 策略模式
Justin | 园豆:980 (小虾三级) | 2008-08-15 09:44
0
不同意,策略模式,此例扩展的不是行为。
blue th | 园豆:110 (初学一级) | 2008-08-15 16:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册