Reputation: 29
public partial class HelloWorldService : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//HttpHelloWorldService.GetInstance().Execute(Request, Response);
//--can the above code be written in the following 3 lines??.......
HttpHelloWorldService.GetInstance();
HttpHelloWorldService hhtt = new HttpHelloWorldService();
hhtt.Execute(Request,Response);
}
}
Note:
-HttpHelloWorldService
is a static class with 2 methods as followings:
-public static HttpHelloWorldService GetInstance()
-public void Execute(HttpRequest request, HttpResponse response)
Upvotes: 0
Views: 55
Reputation: 794
Short answer: No. If this WAS a real singleton implementation you could not successfully call new
at all. If you can call it, you may can replace the code, but then it is definitely no singleton.
The basic idea of singleton is that you only can create one single object of the class. A method like getInstance()
ist used to return this object if it was created before or create it insight this method. You should not be able to create an object on your own by using new
. The constructor of a singleton class should be private. Otherwies you could create multiple objects, what would be against the pattern idea. Use only the return value of getInstance()
to access the singleton object.
A good description of best practice in singleton pattern is given here
Upvotes: 0
Reputation: 230276
Your proposed code doesn't make sense. GetInstance()
is supposed to return an instance, right? Yet you ignore its return value.
HttpHelloWorldService.GetInstance();
And on the next line you create another instance of this class via constructor.
HttpHelloWorldService hhtt = new HttpHelloWorldService();
hhtt.Execute(Request,Response);
Are you sure you know what a singleton is? Because this doesn't look like one at all.
Upvotes: 1