Dale Baker
Dale Baker

Reputation: 339

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!

Upvotes: 0

Views: 596

Answers (1)

Robin Krahl
Robin Krahl

Reputation: 5308

You are right, this is not a factory method. A factory method primarily creates and returns a new instance of a class, maybe doing some additional initialization, logging or other minor tasks.

In your example, there is no need for a factory as all objects have simple constructors. But if you really want to write a factory method, it would typically look like this:

public static GuidedMissileSystem createGuidedMissileSystem() {
    return new GuidedMissileSystem();
}

As you see, this does not have any benefits for simple classes. It would be more helpful if you had to configure the range, the ammunination and many other details of the weapon.

Having a look at your code, I’d suggest that you move the behaviour specific to subclasses where it belongs – to the subclasses. For example, you could add an abstract method createWeapon() to your superclass, and let the subclasses select the appropriate weapon.

Upvotes: 1

Related Questions