假设您正在制作第一人称射击游戏。玩家有多种枪可供选择。
我们可以有一个Gun
定义函数的接口shoot()
。
我们需要类的不同子Gun
类ShotGun
Sniper
,等等。
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 ,并在调用 shoot()
时简单地调用函数fire()
。
public void fire(){
currentGun.shoot();
}
拍摄功能的行为会根据Gun
接口的不同实现而有所不同。
结论
当一个类函数依赖于另一个类的函数时,创建一个接口,该函数会根据实现的类的实例(对象)改变其行为。
例如fire()
,类中的函数Shooter
需要 guns( Sniper
, ShotGun
) 来实现该shoot()
函数。所以如果我们换枪开火。
shooter.switchGun();
shooter.fire();
我们改变了fire()
函数的行为。