Question

I have been learning a lot of inheritance in C#. But am wondering if there are other ways that can be cleaner for component based setups.

I have objects that are all pretty much the same but they have a unique behaviour tied to them, which i currently just override a virtual method.

So every new component i'm making a new class that inherits the Component base class.

Are there cleaner ways to do this in C# rather than have 15 scripts of a class of each component and their unique behaviour?

Pseudo example of the inheritance i have:

Base Class - Component
WaterPump : Component
   //unique behaviour moves water around a system
PowerGenerator : Component
   //unique behaviour creates power units and adds to the system
enter code here
WaterGenerator : Component
   //unique behaviour creates water units and adds to the system

....the list goes on

They have other unique behaviours beyond just simple add/create but just wanted to explain the situation. I have a lot of classes for every single type that requires unique behaviour.

It's starting to get a bit silly - but i don't know how to attach a behaviour to a component so i am not creating a new derived component every single time. Is there any design setup i can do that can improve this?

Was it helpful?

Solution

One way is by passing an instance of an object to the constructor of your component class. This instance contains the data and behavior that may vary, whilst the component class contains that which is common.

Your instances can either be classes with a common base class/interface, or delegates, even lambdas.

Licensed under: CC-BY-SA with attribution
scroll top