I have some functions like:
One that takes input on string and modifies and returns the string
Function that takes a string (holding XML) as input and parses it and returns an object.
For examp开发者_如何学Cle:
public class MyUtils{
public static modifyString(String str){
return someString;
}
public MyObject parseString(String xml){
//Parse XML
return obj;
}
}
- Can I make such functions static, so that anyone can use those without creating instance of my class?
- What if two threads call the function at same time? Is the code thread-safe? If yes/no, how?
- When should I use a singleton object and when should I use static methods?
Yes, just add the
static
keyword. Using the example you have given, you could callmodifyString
like this:MyUtils.modifyString("Some string data");
in your example, as you aren't modifying anything that is stored on your class, it would depend on whether multiple things were accessing what was being passed in. The class itself should be thread-safe.
They are different things, you should use a singleton when you need to use instance data, that is, when you need your class to have attributes or a state. For utility functions, the better option is often to use static methods instead as you are less likely to have a state associated with a utility function.
Yes, you should.
There's no problem specific to static methods; however, if your method references a static field or a mutable argument, there could be conflicts with other threads. If it is referencing a static field, consider using singleton pattern instead.
Use the singleton pattern when the class has state of its own to manage, and particularly to hide such state from clients. If the class just consists of stateless utility functions, you can use static methods and you don't need to use singleton pattern.
Yes, you can make these methods static. In fact these "utility classes" are normally created with static methods.
No, these methods are not thread-safe, a thread could interrupt the method execution and change the value that was currently being worked on.
You should use a singleton when you only need one instance of a class. A good example is a logging class that logs information about the execution of your program. In this case, it wouldn't make sense to use a singleton, because you would be using static methods.
精彩评论