Design Patterns: Singleton

This is the first post in what I hope to be a series of posts on software design patterns. What are design patterns? Design patterns in software development are repeatable code solutions to commonly reoccurring problems. Think of them as templates to common problems that other developers have come up with to solve issues previous developers have dealt with. They help to reduce bugs and can help make your code more maintainable as it grows. Use of these patterns is considered best practices and trust me, smart people have designed them for a reason. So use them. 

Singleton Pattern

A Singleton is a class that has only one instance and provides global access to itself.  In other words, once the class in substantiated, it maintains a reference to itself, and routes all future class construction calls back to the same referenced instance. 

using System;

namespace SingletonPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            MySingletonClass firstInstance = MySingletonClass.Instance;

            firstInstance.TestString = "This was set by firstInstance";
            Console.WriteLine($"Setting firstInstance to {firstInstance.TestString}");

            MySingletonClass secondInstance = MySingletonClass.Instance;
            Console.WriteLine($"Getting secondInstance value {secondInstance.TestString}");

            Console.ReadLine();

        }
    }

    public class MySingletonClass
    {
        private static MySingletonClass instance = null;

        public static MySingletonClass Instance
        {
            get
            {
                if(instance == null)
                {
                    instance = new MySingletonClass();
                }
                return instance;
            }
        }

        public string TestString { get; set; }
        
    }
}

Here you notice that we don't new up the MySingletonClass in main, but just set it to the instance value. The class itself will handle substantiating itself. If the value of the instance is null, then the code will new up the class and set the private instance variable to the new instance, otherwise it will just return it's referenced instance value. This is a very simple implantation and probably not the most thread-safe implementation of the pattern, but the simplest form of the pattern for learning purposes.

Here is a simple but thread-safe version of the pattern

 
public class MySingletonClass
{ private static MySingletonClass instance = null; private static readonly object myLock = new object(); public static MySingletonClass Instance { get { lock (myLock) { if (instance == null) { instance = new MySingletonClass(); } return instance; } } } public string TestString { get; set; } }

There are several other ways to go about implementing this pattern, but the basics are laid out here.  As I said in the beginning, this and other design patterns were created for good reason and we should use them. Why try and reinvent the wheel.  They help solve issues in our code so we don't have to make the same mistakes. So once again use them.

Stellaris

I remember playing a cool PC game back in the late '80s called Starflight, by Binary Systems. It was basically and space exploration, commence and battle space combat type game, similar to the old Star Trek episodes. Now this was back on one of the early 8088 PC clones of the day. Yes, they were called PC clones if they were not original IBM equipment.  Apple existed, but was "Jobless" at the time..

Fast forward like Marty McFly so many years back to the present, and here we are talking about another great space exploration game.  These days, this game genre is called a 4X, like in "eXplore, eXpand, eXploit and eXterminate", but I won't get into that.  It was developed by Paradox Development Studio and published by Paradox Interactive.

This game very much reminds me of a Starflight/Civilization combination game.  It has depth and is not a sit down for a quick 10 minutes type of game. I think my first sitting was in the neighborhood of about 5 hours. I played for about the same time period the next day as well.  I have yet to finish a game, so I don't know if this one suffers from late game boredom when a single faction gets too powerful. Time will time and I will post about it.

Here is a quick summary of the game taken from Wikipedia.

  • Stellaris is a real-time grand strategy game set in space in the year 2200. Players control ships and research vessels among other things, combat is more centered towards the bigger picture, preparation, and strategy. There are also diplomatic options such as alliances and trade agreements with other races. The game begins by picking a species, its ethics, and its technologies. Picking an alien and changing their ethics can change the way information looks; and any species can have any of the ship engineering styles.[2] The player begins with a single planet in their territory, an engineering vessel, a small fleet of warships, a space port, and a science ship. Early gameplay consists of exploring and colonizing space, while mid-game activities focus on diplomacy and governing an empire.[3] In the late game, crisis events can occur that have galaxy-wide implications—for example, an uprising by sentient AI robots or an invasion by extra-dimensional or extra-galactic forces, the former two always being triggered by careless empires. 

Good luck with your expire and see you floating around the galaxy......

 

 

String Interpolation

We have all used the good old reliable String.Format() method, but recently I ran across the newer sleeker way of handling strings in C#. It is called "String Interpolation" and it is definitely a shortcut to constructing strings. Although string interpolation is not a new thing in itself, this implementation in C# is rather nice, once you are used to it.

 

Older Method with String.Format()

public static void OldMethod()
{
            string firstName = "John";
            string lastName = "Doe";

            var formattedString = string.Format("Hello World, My Name is {0}, {1}", firstName, lastName);
            Console.WriteLine(formattedString);
}

 

New Method using string interpolation:    

public static void NewMethod()
{
            string firstName = "John";
            string lastName = "Doe";

            var formattedString = $"Hello World, My Name is {firstName}, {lastName}";
            Console.WriteLine(formattedString);
}

 

There is nothing wrong with the older method and personally I still sort of like it.  Pick the best method for your development style and keep on coding.

Xbox Live Gold Free Games for April

The Telltale game, “The Walking Dead Season 2” is one of April’s free games on Xbox Live.  This is a continuation of one of the main characters from “The Walking Dead Season 1”, Clementine.  The second game of the month is , “Ryse: Son of Rome” and is a third person action-adventure hack and slash type game which follows a Roman centurion Marius Titus.

 

walkingdead

 

Description

The sequel to 2012's Game of the Year continues the story of Clementine, a young girl orphaned by the undead apocalypse. Left to fend for herself, she has been forced to learn how to survive in an unforgiving world. Experience what it’s like to play as Clementine, meet new survivors, explore new locations and make gruesome decisions in this five-part game series of choice and consequence.

 

rome

 

 

Description

“Ryse: Son of Rome” tells the story of Marius Titus, a young Roman soldier who witnesses the murder of his family at the hands of barbarian bandits, then travels with the Roman army to Britannia to seek revenge.