In the previous article we modelled a British World War 2 Sherman tank and it's Firefly variant using the four pillars of object oriented programming (OOP). To remind you, these were encapsulation, abstraction, inheritance, and polymorphism. In this article we mode the same two tanks but using an additional set of guiding principles - composition and the state pattern.
Reproduced here is the original model we came up with using the four pillars of OOP as our guide.
public class Sherman
{
private int milesOfFuel;
private int ammunition;
private boolean bailedOut;
public Sherman(final int milesOfFuel, final int ammunition)
{
this.milesOfFuel = milesOfFuel;
this.ammunition = ammunition;
bailedOut = false;
}
public void move(final int miles)
{
if (bailedOut)
{
return;
}
if (milesOfFuel >= miles)
{
milesOfFuel = milesOfFuel - miles;
System.out.println(string.format("Driving %d miles.", miles));
}
else
{
System.out.println("Not enough fuel!");
}
}
public void shoot()
{
if (bailedOut)
{
return;
}
if (ammunition > 0)
{
ammunition = ammunition - 1;
fire();
}
else
{
System.out.println("Click...");
}
}
public void bailOut()
{
if (bailedOut)
{
System.out.println("Tank already bailed out!");
}
else
{
bailedOut = true;
System.out.println("Crew bailing out!");
}
}
protected void fire()
{
System.out.println("BOOM!");
}
}
public class ShermanFirefly extends Sherman
{
public ShermanFirefly(final int milesOfFuel, final int ammunition)
{
super(milesOfFuel, ammunition);
}
@Override
protected void fire()
{
System.out.println("KABOOM!");
}
}
It is important to stress there is nothing inherently wrong with this model. We can however avoid the use of inheritance by favouring composition. For a small example such as this it is fine to use either approach, but when modelling more complex objects we may favour one approach over the other.
The use of inheritance creates an is-a relationship. The ShermanFirefly is
a Sherman. Instead of this we can model the part that changes between the two
tanks - the main gun - as a separate class. This part is then passed to the
Sherman as a part it needs - creating a has-a relationship. The Sherman
has a MainGun.
Lets take a look at how we can do this by creating a brand new set of classes in Java.
First we will model the MainGun. If you recall the British Sherman came in two
configurations - one with a standard 6 pounder gun, the other with a 17 pounder.
We can define an abstract class called MainGun and then define two concrete
subclasses called SixPounderGun and SeventeenPounderGun respectively. Here
is the code for that.
public abstract class MainGun
{
public abstract void fire();
}
public class SixPounderGun extends MainGun
{
@Override
public void fire()
{
System.out.println("BOOM!");
}
}
public class SeventeenPounderGun extends MainGun
{
@Override
public void fire()
{
System.out.println("KABOOM!");
}
}
Now we can define a single Sherman class that expects an instance of MainGun
in its constructor. The fire method now delegates to the gun instance when asked
to shoot.
public class Sherman
{
private final MainGun gun;
public Sherman(final MainGun gun)
{
this.gun = gun;
}
public void shoot()
{
gun.fire();
}
}var littleTank = new Sherman(new SixPounderGun());
littleTank.shoot(); // Output: BOOM!
var bigTank = new Sherman(new SeventeenPounderGun());
bigTank.shoot(); // Output: KABOOM!
We now have different behaviour without needing to inherit a new tank class.
Lets flesh out our shoot method with the rest of the logic we had before.
public class Sherman
{
private final MainGun gun;
private boolean bailedOut;
private int ammunition;
public Sherman(final MainGun gun, final int ammunition)
{
this.gun = gun;
this.ammunition = ammunition;
bailedOut = false;
}
public void shoot()
{
if (bailedOut)
{
return;
}
if (ammunition > 0)
{
ammunition = ammunition - 1;
gun.fire();
}
else
{
System.out.println("Click...");
}
}
public void bailOut()
{
if (bailedOut)
{
System.out.println("Tank already bailed out!");
}
else
{
bailedOut = true;
System.out.println("Crew bailing out!");
}
}
}
Phew! That's a lot of conditional logic (if statements) for such a small
class. It would be nice to encapsulate the conditional bits of code in their own
classes, and not have so much branching happening. We can as it turns out do just
that, using a design pattern called the state pattern.
Notice that our tank class has three main states it can be in:
We need to introduce three classes to model the behaviour of these states, all
extending the same abstract base class. The two actions shoot and bailOut
can be changed so they just delegate their actions to an instance of these
classes. This state class can be referenced by the main Sherman class.
The listing that follows has a lot of changes in it. Take time to study it,
and make sure to type it in and run it to understand what is going on. In a real
codebase you might not define the state and gun classes as inner classes, but
each in their own .java file instead.
public class Sherman
{
// Composition classes.
public static abstract class MainGun
{
public abstract void fire();
}
public static class SixPounderGun extends MainGun
{
@Override
public void fire()
{
System.out.println("BOOM!");
}
}
public static class SeventeenPounderGun extends MainGun
{
@Override
public void fire()
{
System.out.println("KABOOM!");
}
}
// End of composition classes.
// State pattern classes.
public abstract class TankState
{
protected final Sherman tank;
public TankState(Sherman tank)
{
this.tank = tank;
}
public abstract void shoot();
public abstract void bailOut();
}
public class BailedOutState extends TankState
{
public BailedOutState(Sherman tank)
{
super(tank);
}
@Override
public void shoot()
{
System.out.println("Can't shoot, tank bailed out!");
}
@Override
public void bailOut()
{
System.out.println("Tank already bailed out!");
}
}
public class CrewedWithAmmunitionState extends TankState
{
private final MainGun gun;
private int ammunition;
public CrewedWithAmmunitionState(
final Sherman tank,
final MainGun gun,
final int ammunition)
{
super(tank);
this.ammunition = ammunition;
this.gun = gun;
}
@Override
public void shoot()
{
if (ammunition > 0)
{
ammunition = ammunition - 1;
gun.fire();
}
else
{
System.out.println("Click...");
tank.state = new Sherman.CrewedWithoutAmmunitionState(tank);
}
}
@Override
public void bailOut()
{
System.out.println("Crew bailing out!");
tank.state = new Sherman.BailedOutState(tank);
}
}
public class CrewedWithoutAmmunitionState extends TankState
{
public CrewedWithoutAmmunitionState(Sherman tank)
{
super(tank);
}
@Override
public void shoot()
{
System.out.println("Click...");
}
@Override
public void bailOut()
{
System.out.println("Crew bailing out!");
tank.state = new Sherman.BailedOutState(tank);
}
}
// End of state pattern classes.
// Tank model.
protected TankState state;
public Sherman(final MainGun gun, final int ammunition)
{
state = new Sherman.CrewedWithAmmunitionState(this, gun, ammunition);
}
public void shoot()
{
state.shoot();
}
public void bailOut()
{
state.bailOut();
}
// End of tank model.
// Test code.
public static void main(String[] args)
{
var tank = new Sherman(new Sherman.SeventeenPounderGun(), 2);
tank.shoot();
tank.shoot();
tank.shoot();
tank.bailOut();
tank.bailOut();
}
}
Output should be as follows:
KABOOM!
KABOOM!
Click...
Crew bailing out!
Tank already bailed out!
There we go, we looked at composition over inheritance and the state pattern to model the British Sherman and Sherman Firefly tanks. This was a more complex model than the last one, but it keeps everything nicely separated into its own class and is hence easier to maintain and develop further.