Rusty Divine

Live, Love, Learn, Teach

Learning Design Patterns - Singleton

A while ago now I bought this book on design patterns. At first glance, this book may seem a little silly, childish even, because of all the cartoonish thought bubbles on amusing old photographs and the crosswords and such. After reading the introduction that explained how making learning fun and interesting, and how they were going to trick my brain into paying attention to an otherwise dull subject, and how they sneaked in repetition and other memory inducing tricks, it started to make a lot of sense to me. Even though this book is targeted more at Java developers and I am a .Net developer, it is general enough and explains the concepts well enough that I have no problems understanding it.

This is the first post in my new series on learning design patterns. To say it another way, I am going to be learning these patterns along the way, so any helpful comments and corrections from the more experienced would be appreciated - just be kind!

To start, I figured I would select the classic and deceptively simple Singleton pattern. I guess I could start by writing a monologue about why patterns are important, but I'll leave that one to the academics; I just want to broaden my horizons and am more interested in application. Besides, I know a guy who got a great job in part because he knew how to write a Singleton pattern during his interview (not a bad interview question, I'd say).

What is it?
The Singleton pattern is intended to create one and only one instance of an object that can be accessed globally across an application.

Where is it used?
The Singleton pattern works well in many situations. Common uses include managing connection or thread pooling, application configuration settings, logging, dialog boxes, incremental or other counters, and device drivers.

But why?
Why not just create global variables or static methods? The Singleton pattern is a design convention, a best-practice of sorts and generally it would be better to pick it over the other two methods. Singleton gives you a global access point like a global variable, but is intended to reduce overhead by not initiating the object until it is called, unlike global variables that would be initiated at startup even if they are never used and guarantees that there is only one instance in memory.

OK, and how is it implemented?
Have you ever seen those kooky UML diagrams for design patterns? Crap, I'd have better luck baking a German Chocolate Cake from a recipe in German than writing code based on one of those. Suffice it to say, I have to spell it out instead.

The key ideas are: 1) Use a private constructor so that only the class itself can initiate itself, which will allow it to regulate itself. 2) Declare a private static variable of the same type as the class itself to hold a reference to the object in memory. 3) Create a public method that checks to see if the object exists in memory, if so, return a reference, if not create it first then return a reference. 4) Add other code as needed, but don't allow sub classing (which is impossible anyway since the constructor is private). 5) When it comes to threading, be super careful; it is easy to goof up and allow two instances of the object to exist.

//general example from the book; Java?
public class Hermit {
	private static Hermit singleInstance;
	private Hermit() {}
	public static Hermit getInstance() {
		if (singleInstance == null) {
			singleInstance = new Hermit();
		Return singleInstance;
//Direct port to C#
class Hermit 
  //prevent optimization reordering with volatile keyword
  private static volatile Hermit singleInstance = null;
  protected Hermit() {}
  public static Hermit getInstance() {    
    if (singleInstance == null) {
	// double-check lock for thread safety and to 
	// reduce overhead if instance exists
            lock (typeof(Hermit)) {
                if (singleInstance == null) {
                    singleInstance = new Hermit();
        return singleInstance;      
//Simplified C# code that relies on .Net Framework's intrinsic abilities
sealed class Hermit  //sealed=not inheritable
   private Hermit() {}
   public static readonly Hermit getInstance = new Hermit();
   //.Net Framework guarantees thread safety on 
   //static type initialization, and only initializes static
   // properties when the method is first called.

Further Reading

Hourly vs. Salary

About six months ago, I switched jobs. The former company was crumbling, the current company is a behemoth. Jumping jobs brings change; for instance, I am no longer a salaried employee. I now punch the clock and am not guaranteed 40 hours of work per week in what my new company terms a "flex" position.

For some, the thought of a fluctuating paycheck and being sent home early would put a puddle in their shoe. It is unnerving at times to consider the worst case scenarios of being forced to make life style sacrifices, losing a car, a house, or even a marriage. And there is a general feeling of lack of control, of letting loose of the reins and watching the team of horses run where they may.

Why do I feel completely comfortable and even more content as an hourly employee?

Still in Control
Really, I am still in control. If the ends stop meeting and the creditors start calling, then I can pick up and move on. The market for my skills and experience is quite healthy, and I'm in one of the best locations in the world to take advantage of the opportunities (Seattle, Washington, USA, that is).

In fact, I may have more control. I can come and go as I please. Best of all, I don't work for free anymore! At a salaried consulting job, it is common to work 45 hour weeks for 40 hours of pay. Now, though, I will get paid for what I work, and if it's over 40 then I get time-and-a-half pay.

I've also noticed that I am more efficient now. I surf the Internet less, I am more conscientious about putting the correct time on my time card (no more putting 8 hours down even though I took a 90 minute lunch) and I try to focus on my tasks. I feel more accountable.

A Reprieve from Corporate Ladder
I spent the last 5 years trying to get noticed in the corporate environment. Noticed I got, but at my last job, there were 30 executives in a company of 120 people - I didn't feel like there was any room for me up there (it was super saturated). In fact, when I asked about the chance of a promotion at my last, fateful review, I was told the company had no notion of promotion. How did all those managers get up there then? Well, that's another story, but it essentially had to do with the company expanding by opening more offices or buying other small companies and keeping all of the managers around. Small company, many offices.

Now, at my new job, I just go in and someone hands me some work to do. I don't feel the pressure to get noticed, only to do my job as professionally as I can. Earlier, a coworker asked me if I was going to the company's open house. I asked, "Why the hell would I want to do that?" (I can be blunt at 7 am, especially since I recently gave up coffee) He said something along the lines of schmoozing and rubbing elbows. I have no ambitions at this company outside of doing my job the best I can, and I feel happy that I don't have to or feel the need to go to the gathering (I am an introvert, BTW, an ISTPto be exact).

Moving out of Dodge
Remember what you were like as a teenager, and maybe even into college? My guess is that when you moved out of your parents house (or when you do) your character will change in a very perceptible way. And here's the rub: when you go back home to visit, you will run the risk of falling back into the old role and may feel like a marionette on strings - not totally in control of yourself, your emotions or actions.

Moving on is a great chance to change yourself for the better. You can adopt a new you, because you will have brand new routines, environment, and people to interact with. I have grown professionally two pegs since I left my old job just a week ago, because it has given me the chance to reinvent myself. I fell into ruts at my old job; gossip, negativity, apathy, cynicism. I knew at the time that it really wasn't like me to be acting in some of those ways, but the more I acted that way, the more my environment changed to foster more of the same. Now, at my new job, I can try to stay away from attitudinal pot holes. I can remember to think clearly before I respond. No one has any preconceptions on how I think or solve problems, I am once again free to just be myself.

Money, Money, Money, Money
I am a capitalist at heart, and money speaks loudly to me. At my salaried job, I told my boss how much I should be making, and he told me to go find a job that would pay me that much. So I did. And, at the hourly job I took, if I work 30 hours a week, I'll be making more than at my salaried job - talk about a difference!

I have a large grudge about ageism - people getting paid more than I do based on age alone. Yes, older people have more experience and are generally better able to cope with stressful situations and lead. Generally. Let me tell you this though; when it comes to technical experience in my field, a ton of people have as much experience as I do, some, but not many have more. The computer industry is different than most industries because it is so damn new. My buddies and I were working on starting a dial-in bulletin board system (BBS) that hosted pornographic material before the world wide web had its first graphical browser. (We coulda been rich if we realized how on the mark we were back then in 1990!) When I sit next to a guy who is 40, is not managing anyone, and knows less about programming, but is making 50% more than me because he is 15 years older, I tend to get a little cynical. (But that was the old me, right? You bet; I left that stinking job.)

At my new job, I do have some benefits like 401k and cheap healthcare, but they are more limited than I had at my old job, or would have if I was full time here. I am lucky that I can go through my wife's health care (which is better even if it was free for me here), which is the big concern for me. There are no bonuses I'm missing out on, but I do only get 5 hours of vacation per period instead of 8.

Turns out I was Right
And, conveniently enough, it turns out that my new job is much more fun than my old job. I like my office space better, my coworkers are a breath of fresh air (for now), and I have new challenges, new experiences, old experiences and lessons to share, and a new outlook on my job.

It could have been much worse; my new job may have been awful just as easily as it turned out not to be. I would like to meet the person who knows how to get a good feeling of what it will be like working at a company before they start working there. For me, I just have to jump in feet first and start swimming.