Which one is better Singleton class or Shared (static) Member functions
I would like to understand the Pro & Cons in using the commonly used methods via Singleton class against Shared (Static) members of a class in VB.Net. It could be in ter开发者_Go百科ms Time, Space complexity or best practices.
I have a BankAccount class with methods doing some business logic.
GetBalance()
GetLast5Credits()
GetMiniStatement()
and some write operations too.
In this scenario, which method of accessing the member functions is better? Shared or Singleton?
Neither. You should use a dependency injected instance. i.e. you don't build the assumption that there is only one instance into your code. You just happen to create a single instance. That way you can can change your software to use more than one instance easily.
The basic idea here is that you take the bank account as a parameter in the constructor of your classes:
class MyClass
{
private readonly IBankAccount bankAccount;
public MyClass(IBankAccount bankAccount)
{
this.bankAccount=bankAccount;
}
}
Since creating such a class manually can be annoying if you need to pass in a lot of stuff you usually use a dependency injector/IoC container to do it for you.
Static methods should be used for stateless side-effect free helper functions. Math
and Enumerable
have good examples for static methods.
In general you should avoid global mutable state. And a bank account is clearly mutable. Here a classic singleton is the lesser evil(you can substitute the implementation for testing purposes), but it's still a bad choice.
that depends on if you are going to have more then one BankAccount in your application. Basically, Static or Singleton means you can have only one instance of the object in question--in this case BankAccount. a Bank with only one BankAccount is a pretty poor bank, if you ask me. :) Here is a pretty decent explanation, but the example code is in C#
I don't believe you want either here...
but for future reference, a Shared class as you put it should not have anything to do with maintaining state - each static method should only work with the parameters passed in. This makes this type of class useful only for utility functions.
A singleton would only be useful here, if you were persisting the data relating to the account in memory. Then you could implement a singleton as an indexer, containing a collection of bank account records, but you would have to be mindful of race conditions.
Personally, I prefer the singleton class for the sake of unit testing. You can mock an instance class, but you can't mock a static class.
精彩评论