接口的有点:
@1、规范继承制必须实现共有的方法、多继承可实现继承者实现不同功能
@2、管理者只需规范接口,把实现交给程序员即可完成整体统一
例子下载:
http://download.csdn.net/detail/ggbb190/6549981
1、制作接口,规范动物通用行为,用来规范所有动物的共性,要求继承者统一实现
interface ianimalbehavior
{
/// <summary>
/// 吃
/// </summary>
string eat();
string drink();
string play();
string sleep();
}
2、定义狗dog的类、猫cat的类,集成子动物行为接口
class dog : ianimalbehavior
{
public string name = "";
public string eat()
{
return name+"已eat";
}
public string drink() { return name + "已drink"; }
public string play() { return name + "已play"; }
public string sleep() { return name + "已sleep"; }
public string jump() { return name + "已jump"; }
}
class cat:ianimalbehavior
{
public string name = "";
public string eat()
{
return name+"已eat";
}
public string drink() { return name + "已drink"; }
public string play() { return name + "已play"; }
public string sleep() { return name + "已sleep"; }
}
3、实际使用是这样的
cat littlecat = new cat();
littlecat.name = "猫";
this.textBox1.Text += littlecat.drink()+"\r\n";
this.textBox1.Text += littlecat.eat() + "\r\n";
this.textBox1.Text += littlecat.play() + "\r\n";
this.textBox1.Text += littlecat.sleep() + "\r\n";
dog littledog = new dog();
littledog.name = "littledog";
this.textBox1.Text += littledog.drink() + "\r\n";
this.textBox1.Text += littledog.eat() + "\r\n";
this.textBox1.Text += littledog.play() + "\r\n";
this.textBox1.Text += littledog.sleep() + "\r\n";
4、突然过几天又发现猫要抓老鼠,但是代码由于不是同一批程序员写的,所有不想更改以前的基类代码,所有抓老鼠的功能我们既可以写到cat中的方法,也可以抽象出一个抓老鼠接口,因为这样将来有蛇、老鼠夹、耗子药的对象出现都可以继承抓老鼠接口。为什么不写到ianimalbehavior接口呢?因为如果写在这里dog或其他动物必须实现该方法,但其本身并不具有该功能,所以不能抽象到这个接口内,而是新建一个接口,让cat多继承自不同接口。
class cat:ianimalbehavior,ianimalcatch
{
public string name = "";
public string eat()
{
return name+"已eat";
}
public string drink() { return name + "已drink"; }
public string play() { return name + "已play"; }
public string sleep() { return name + "已sleep"; }
public string catchmouse() { return name + "已catchmouse"; }
}
5、最终实现
cat littlecat = new cat();
littlecat.name = "猫";
this.textBox1.Text += littlecat.drink()+"\r\n";
this.textBox1.Text += littlecat.eat() + "\r\n";
this.textBox1.Text += littlecat.play() + "\r\n";
this.textBox1.Text += littlecat.sleep() + "\r\n";
//新增
this.textBox1.Text += littlecat.catchmouse() + "\r\n";
dog littledog = new dog();
littledog.name = "littledog";
this.textBox1.Text += littledog.drink() + "\r\n";
this.textBox1.Text += littledog.eat() + "\r\n";
this.textBox1.Text += littledog.play() + "\r\n";
this.textBox1.Text += littledog.sleep() + "\r\n";