I am trying to make a simple game where you have a weapon and you can attach things to the weapon that changes the behaviour of said weapon.

But how do you design code for this behaviour overriding/modifying.

Normally I would use virtual method overrides when I want a derived class to have a different behaviour to the base class, but it doesn't make sense in this case because the attachments are not derived classes of the given weapon, they are instead something tacked on to the weapon compositionally.

I have no idea how to approach this to give me the freedom and flexibility to attach anything I want to a weapon, so some advice on what my options are would be welcome.


migrated from softwareengineering.stackexchange.com Aug 9 at 2:19

This question came from our site for professionals, academics, and students working within the systems development life cycle.

  • 1
    \$\begingroup\$ Using composition, weapons can delegate to attachments, when present. You may find arranging attachments as classes having a common base/interface useful. What is delegation? That's just what we call when one class's method implementation defers to another's. \$\endgroup\$ – Erik Eidt Aug 8 at 23:39
  • \$\begingroup\$ Sorry i'm still a bit new to this. So is a delegate a reference to a method in the class of the attachment? Are you able to write a crude example so i understand the design pattern flow - i should be able to figure it out from there. \$\endgroup\$ – WDUK Aug 9 at 2:02
  • 1
    \$\begingroup\$ @ErikEidt Add a code example and that could be a solid answer. :) \$\endgroup\$ – DMGregory Aug 9 at 2:29
  • \$\begingroup\$ Did this really need to be migrated to game dev? This is about code design structuring - not really game development specific...i just used a game as an example to explain what i was on about. Would it be any less valid on S.E if i had used a non game example... \$\endgroup\$ – WDUK Aug 9 at 2:32
  • \$\begingroup\$ Study the Composite Pattern. Works well if your weapons functions never change. Just what they do when you use them. \$\endgroup\$ – candied_orange Aug 9 at 3:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.