Class with only Methods, Should be Singleton or Static

I have lot of service classes in my application which don't have any state(any fields, properties) but have methods. Should I make this class as static or create a single object of this class and use the single object through out the life cycle of application

Upvotes: 2

Views: 176

Answers (4)

Habib
Habib

Reputation: 223352

Should I make this class as static or create a single object of this class and use the single object through out the life cycle of application

Declare them as static class, with all methods being static. This will force you not to have instance members later in your code.

You may see: What is the difference between all-static-methods and applying a singleton pattern?

Upvotes: 3

IAbstract
IAbstract

Reputation: 19881

In most cases, you can make the class and it's members static.

However, if you plan on any unit testing of the service classes, you will need an instance whereby an interface would be handy. Since you cannot implement an interface on a static class, you would be required to use the singleton pattern and implement the interface.

Upvotes: 1

Emmanuel N
Emmanuel N

Reputation: 7449

Singletons can implement Interface, while static class can't. So if your code will benefit from interface(example - dependence injection) then use singleton other wise static will surfice.

Upvotes: 2

Bob Horn
Bob Horn

Reputation: 34325

You only need this class to be a singleton if you need to implement interfaces or derive from other classes. If you don't have that need, go with a static class.

Upvotes: 7

Related Questions