mercredi 8 juin 2016

Returning Void For A Factory Method Pattern

I am currently completing an assignment for class and one of the questions wants me to reconstruct some of the sample code given to me.

without being too precise, they have an abstract class with several different subclasses and each different subclass is assigned a weapon depending on what kind of subclass it is.

e.g.

if (this.getClass().getSimpleName().equals("FighterJet")) {
    this.weapon = new GuidedMissileSystem();
    System.out.println("FighterJet " + id + " equipped with " + weapon.getClass().getSimpleName());
} 
else if (this.getClass().getSimpleName().equals("AttackHelicopter")) {
    this.weapon = new GrenadeLauncher();
    System.out.println("AttackHelicopter " + id + " equipped with " + weapon.getClass().getSimpleName());
...

it then prints a string to the console which has the name of the subclass and the weapon.

in the abstract superclass it has a series of if statements to check what subclass it is and to assign the proper weapon to it and print the proper string.

they suggested looking at a design pattern and i opted for the 'factory method', however, since it's printing a string that has the name of the subclass in it, i decided to not return anything in this method and just assign the weapon through this syntax:

    this.weapon = //whatever weapon

and returning void.

Is this still considered the factory method? I suspect it isn't.

Thanks!

Aucun commentaire:

Enregistrer un commentaire