Main Site Documentation

Static class vs. Singleton pattern


#1

I’m taking the time to refactor one of my apps. I was pretty new to embedded programming when I started my whole .NET Micro Framework journey and want to see if I can clean up some of the corners I cut. I’ve learned a lot more about Object Oriented Programming (OOP) and I’m trying to take advantages of that approach where it makes sense.

In my current app I have classes for a variety of things that only appear once in my system. For example, I have one GPS class, one fluorometer class, one Iridium modem class and so on. All of those classes communicate to the state machine in main() through a FIFO queue that is also implemented as a class. I declared all of these classes as static mostly out of ignorance and fear of the garbage collector disposing of something I need and/or running for an unacceptable length of time. However, now I that I understand OOP and design patterns a little better, it might make sense to implement all those classes as Singletons.

So the question for you experienced OOP types is: what are the pros and cons of singletons vs static classes?

Thanks


#2

A static class alone is not thread-safe. This is required reading.

Ian