Skip to content
Advertisement

Trouble decoupling in Java using switch statements [closed]

currently I am making a small type game, which in my player class I have far to many importants and dependencies.

So I have decided to separate the switch statements in its own individual class to be called in a method.

For context the player code

JavaScript

So the code above is my Player class, I would like to put the addBasic/Good/Great weapon attachments in another separate class file, to then allow better decoupled code. I am not sure how to do this with a switch statement.

Any ideas on how to approach this?

Edit:

The switch methods are being called form the main:

JavaScript

The Abstract accessory class:

JavaScript

An accessory extending AccessoryDecorator:

JavaScript

So the objective is to have:

JavaScript

In a class of its own, to then be able to call the switch with result, which will then add to the values of the gun selected.

I cant seem to think how to return the accessory depending on what accessory is created.

Advertisement

Answer

You could make a base class with some functionality and then add code by the means of extension. Another option is making a utility class with only static functions that you can call to manipulate the passed object, like this:

JavaScript

But in your case I recommend you create another class: “EquipedWeapon”. This class will have its own Weapon field and possibly multiple Attachment fields. You can put the code for changing attachments in there, and even add some methods for getting stats about the weapon with the attachments on it, like the damage or bullet spread or wtv, then create a getter for the weapon inside of PlayerSingleton.

I’d also recommend creating an AttachmentManager class in your game that holds all attachments and allows you to select them using various methods. Or you could make all attachments extend one Attachment class that holds a static list of all attachments. If you add the name as a field inside the attachment class, you can then create a static method that iterates over all attachments and finds one with the right name and returns it. Or use a static Hashmap<String, Attachment>.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement