Hidden Gem: Singleton Factory in C#(cognitivecoding.com)

submitted by shivashankarpshivashankarp(335) 4 years, 2 months ago

Simple and generic implementation of singleton factory in C#.

5 comments |category: |Views: 343

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by yesthatmcgurkyesthatmcgurk(4063) 4 years, 2 months ago 0

Ugh, I hate Blogger blogs. The comment system is so fucked up.

The pattern is okay, but there is a problem with it. Generic implies that it works everywhere (as long as the constraints are met). This pattern only works if the constructor of the object has a nonpublic constructor. You can't create a constraint for this, so there is no guarantee that the object is a singleton as the pattern cannot be enforced. You still have to rely on the coder to implement the pattern correctly, and if you have to rely on this, then its pretty much the same as saying, "Hey, only create one instance of this class per app domain, k?"

If i were to use this (and I wouldn't), I'd use reflection to see if the class has a public constructor, and if it does, I'd throw an invalid operation exception to prevent the situation described above. Its a little bit better, but still not as perfect as the static constructor singleton pattern.

Reply

posted by powerrushpowerrush(3873) 4 years, 2 months ago 0

It's nice for those of us that like to play with sharp tools, though.

http://codebetter.com/blogs/jeffrey.palermo/archive/2007/12/02/who-is-to-say-that-my-knife-is-too-sharp-for-my-own-good.aspx

Reply

posted by yesthatmcgurkyesthatmcgurk(4063) 4 years, 2 months ago 0

I get the point. But is it a singleton pattern if you can create more than one instance per app domain? Its more of a "somewhat singleton" pattern. As a somewhat singleton, its great. No doubt about that.

Reply

posted by CVertexCVertex(325) 4 years, 2 months ago 0

There's a similar pattern implemented with a new() constraint in NGenerics.
I like it alot more than this one, because a singleton doesn't need to be a class.

This pattern is great for avoiding the non-generic singleton everywhere. The public constructor is a small disadvantage.

Reply

posted by simplicityiskeysimplicityiskey(650) 4 years, 2 months ago 0

This is great! I think too many developers underrate the use of patterns. Design patterns provide you with so many great things (e.g. leaner code, faster ramp-up time for new developers, just to name a couple).

Reply

information Login or create an account to comment on this story