I am struggling to choose the perfect design pattern for this scenario :
When I click on the Browse button on my swing UI, a specified URL must be opened up on the web browser. This functionality is achieved inside this utility class which looks like this :
//inside action Listener of the browse button I call the openURL method of the below class
class webBrowserUtility(){
void openURL(String url){
........
}
}
Design Pattern Methods
Approach 1) I can go ahead and create new instance of the above class and invoke openURL().
Approach 2) Singleton : Make the WebbrowserUtility class a singleton and retain a static instance of that class in memory to be able to call the method whenever needed.
Approach 3) static method : Make the openURL() method static and call WebbrowserUtility.openURL(url) as needed.
In my first approach, I am worried that it might be inefficient as, every click on the browse button will create a new instance of the WebBrowserUtility class. I am confused between which approach to adapt between choice 2) and 3). Can you please help me choose the best among these three design patterns for this scenario? Or is there a better design pattern that can be adapted for the same?
Firstly, I recommend that you not overly worry about the possibility of a performance/efficiency issue at this stage unless you have some concrete reason to believe it will be a problem. Wait and see if it actually is a problem, and then address it accordingly. But you might well find that there’s nothing to worry about.
So, the question is, does your
WebBrowserUtilityuse any non-static member variables (i.e. instance data) of your class?If it does, then you’ve got to go with approach 1. and create a new instance every time.
If it does not, then I’d be inclined to go with a static method and make the
WebBrowserUtilitya static class rather than implement a singleton. You don’t really need there to be only one instance, which is what the singleton pattern is for. And the static method on a static class solution gives you the easy accessibility you need. The downside is that if you’re writing unit tests for this, properly unit testing a static method is problematic.