Thursday 18 July 2013

When to create an interface

Consider you are making a first person shooting game. The player has multiple guns to choose from.
We can have an interface Gun which defines a function shoot().
We need different subclasses of Gun class namely ShotGun Sniper and so on.
class ShotGun implements Gun{
    public void shoot(){
       \\shotgun implementation of shoot.
    } 
}

class Sniper implements Gun{
    public void shoot(){
       \\sniper implementation of shoot.
    } 
}

Shooter Class

The shooter has all the guns in his Armour. Lets create a List to represent it.
List<Gun> listOfGuns = new ArrayList<Gun>();
The shooter cycles through his guns,as and when needed, using the function switchGun()
public void switchGun(){
    //code to cycle through the guns from the list of guns.
    currentGun = //the next gun in the list.
}
We can set the current Gun , using the above function and simply call shoot() function, whenfire() is called.
public void fire(){
    currentGun.shoot();
}
The behavior of the shoot function will vary according to different implementations of the Gun interface.

Conclusion

Create an interface, when a class function is dependent on a function from another class, which is subjected to change its behavior, based on instance(object) of the class implemented.
for e.g. fire() function from Shooter class expects guns(SniperShotGun) to implement theshoot() function. So if we switch the gun and fire.
shooter.switchGun();
shooter.fire();
We have changed the behaviour of fire() function

No comments:

Post a Comment