面向对象基础-重构
动物中如果又有小牛,小羊来报名,需要参加“叫声比赛”,如何办?原始的方法只要继承即可。
但是,我们会发现,Cat、Dog、Bull,Sheep中除了构造方法Shout()之外,几乎没有什么差异。这样子的不好使,比如把shout()中的“我的名字是**”改成“我叫**”,那么四个类都需要改变。
这个时候,我们需要这样子做了。我们还是要把Shout()放到Animal类中,但是现在就不是virtual的了。
此外,我们还需要添加一个getShoutSound()的方法,表示判断是“喵”还是“旺”。 
1: class Animal
   2:      {   3:         ..................................................4: public string Shout()
   5:          {6: string result = "";
7: for (int i = 0; i < shoutNum; i++)
8: result += getShoutSound() + ",";
9: return "我的名字是" + name + "," + result;
  10:          }11: protected virtual string getShoutSound()
  12:          {13: return "";
  14:          }  15:      }  16:   17: class Dog:Animal
  18:      {19: public Dog()
20: : base()
  21:          {  22:          }23: public Dog(string name)
24: : base(name)
  25:          {  26:          }27: protected override string getShoutSound()
  28:          {29: return "旺";
  30:          }  31:  } 
                    
                     
                    
                 
                    
                 
 
        
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号