假设你正在制作一款第一人称射击游戏。玩家有多种枪可供选择。
我们可以有一个接口Gun,它定义了函数shoot()。
我们需要不同的子类枪类,即霰弹枪狙击手等。
ShotGun implements Gun{
public void shoot(){
\\shotgun implementation of shoot.
}
}
Sniper implements Gun{
public void shoot(){
\\sniper implementation of shoot.
}
}
射击类
射手把所有的枪都装在他的盔甲里。让我们创建一个List来表示它。
List<Gun> listOfGuns = new ArrayList<Gun>();
射手在需要时使用switchGun()函数循环使用他的枪。
public void switchGun(){
//code to cycle through the guns from the list of guns.
currentGun = //the next gun in the list.
}
我们可以使用上面的函数设置当前的Gun,当调用fire()时,简单地调用shoot()函数。
public void fire(){
currentGun.shoot();
}
shoot函数的行为将根据Gun接口的不同实现而有所不同。
结论
当一个类函数依赖于来自另一个类的函数时,创建一个接口,而另一个类根据实现的类的实例(对象)改变其行为。
例如,Shooter类的fire()函数期望枪械(Sniper, ShotGun)实现shoot()函数。
所以如果我们换枪开火。
shooter.switchGun();
shooter.fire();
我们已经改变了fire()函数的行为。