ilyketurdles
ilyketurdles

Reputation: 113

Static abstract objects with virtual methods

I'm working on a personal project and I've run into an issue.

I have object a couple of objects that have the same properties, methods, etc. The only things that differ are their names, values of properties, and the implementation of the methods. They also need common default implementation of methods. So right away, an interface is out of the question.

So I created a base class with the properties and "default" methods. But this base class needs to be abstract. The methods are virtual so they can be overridden.

The reason I need them to be static is that objects will be properties of other objects.

So, for example, the objects referenced above are (for sake of simplicity) objX, objY, objZ. They are derived from their base, objW.

objContainer is a completely unrelated object, but it has a property of type objW, which is an instance of either objX, objY, objZ.

objX, objY, and objZ will never change. Their properties will all be readonly. So multiple objects of instance objContainer will have objX, objY, or objZ.

public class objContainer1
{
    objW processor = new objY; 
}
public class objContainer2
{
    objW processor = new objY; 
}

How do I go about doing this? I wanted to keep them static so I don't have multiple instances of the same objects, when all of them are the exact same, really.

Do I use a singleton? Factory pattern?

I'm lost as to which direction to go with this (if any). Maybe I'm overthinking it and there's a very simple solution/

Upvotes: 1

Views: 97

Answers (1)

rory.ap
rory.ap

Reputation: 35338

You want to use static classes sparingly. There are obvious downsides to static classes, such as the inability to take advantage of the polymorphic nature of class inheritance since you can't inherit from a static class. The only time you want to use a static class, really, is when you have something like a set of related tools that you want to make available across your application and for which you don't need to maintain any state. Think of the System.Math class, for example: a set of math functions that you can use anywhere in your application. Having an instance of that class doesn't really make any sense, and it would be rather cumbersome and unnecessary.

I would suggest sticking to non-static classes and creating instances of those classes. If you should only ever have one instance of your class, then you should use a singleton, as you suggested.

Upvotes: 6

Related Questions