Singleton Design Pattern

Singleton Design Pattern

WHAT?

In some cases, it is important to have exactly one instance of a class. Although you have many electric appliance in your house but you have only one main switch box for incoming electricity in house. You have only one control panel in your windows Operating system. There is only one payroll software system to handle paychecks.

How do you ensure that you have only one instance of a class and that is also easily accessible? A global variable makes an object accessible but it does not prevent you from instantiating multiple objects.

A better solution is to make class itself responsible for keeping track of its single instance. The class can ensure that no other instance can be created and it can provide a way to access the instance. This is called Singleton Pattern.

WHEN?

Whenever you are looking for single point of connection to use at multiple places. Best example is logging. To access logging process in a program in various classes you don’t want to end up with creating objects of logger class and access methods. Rather you would prefer to have one instance of class and use everywhere in solution or project. Thus in Singleton pattern, Information flows in one way.

HOW?

Client can access a Singleton instance solely through Singleton’s Instance operation. Instance is a class operation similar to static member function in C++.

PRO?

The Singleton pattern has several benefits.

1. Controlled access to its solo instance: Singleton class encapsulates its solo instance, which has strict control over how and when client can access it.

2. Flexibility over instances: Because the class controls the instantiation process, the class has the flexibility to change the instantiation process too.

CONS?

1. Overhead: Though the is minimal time but still there is some overhead involving to check whether an instance class already exists every time an object request a reference.

2. Object lifetime:




HOW TO DESIGN?

Following implementation is singleton Pattern given in MSDN

using System;
public class Singleton {
	private static Singleton instance;
	private Singleton() {}
	public static Singleton Instance {
		get {
			if (instance == null) {
				instance = new Singleton();
			}
			return instance;
		}
	}
}

Look at the code, you will notice at line 5; class constructor is defined as private which ensures that no other object can create a new instance of this Singleton class.

This implementation has two advantages:

1. Because instance has created inside the instance property method, the class can perform another actions as well like instantiating subclasses, though it may introduce unwanted dependencies.

2. Instantiation is not performed until an object asks for the instance.

The disadvantage of this pattern is that it is not safe in multi threaded environment. If at the same time, two separate thread ask for instance, it will check at line 10 before creating a instance. At this point, there is a possibility of race condition. To avoid that, Static Initialization is the solution.

Static Initialization

public sealed class Singleton
{
	private static readonly Singleton instance = new Singleton();
	private Singleton() {}
	public static Singleton Instance
	{
		get
		{
			return instance;
		}
	}
}

In this strategy, member of the class is creating the instance first time inside class itself. The Common Language Runtime (CLR) will take care of variable initialization. The class is marked sealed to prevent any derivation. The variable marked as read-only, which means that it can be assigned only during static initialization or in the class constructor.

For detailed implementation of Singleton Design Pattern refer the section 4.

Reference:

1. Design Pattern: Element of Reusable Object-Oriented Software By: Erich Richard Ralph and John.

2. MSDN Library.

How to handle Mixed Content blocker in Firefox via WebDriver

In new version of Firefox, recently I encountered mixed content blocker where page given in specific frame was not loading. I noticed on the top of the screen in latest Firefox there is an icon on the top of the screen


1

What is Mixed Content?

You can find very detailed explanation on Mozilla support page but just for quick explanation if you don’t want to read there:

“HTTP is not encrypted but HTTPS and if you have a http content into HTTPS page then there are chances that your content can be hacked and its known as Mixed content”

How to Handle manually

To handle that you need to click on dropdown next to Keep Blocking and select option “Disable Protection on This Page”.

2

After disabling, your content will display but with orange warning  triangle as below.

3

To learn more about this refer:

https://support.mozilla.org/en-US/kb/how-does-content-isnt-secure-affect-my-safety?as=u&utm_source=inproduct

How to handle using WebDriver

To handle this, you need to change the preference setting before starting the Firefox driver. To access preference type about:config in address bar, accept the agreement and type “mixed_content” in search field, you will see the following.

4

security.mixed_content.block_active_content  : false

security.mixed_content.block_display_content : true

This is causing content not to display. Before launching Firefox driver, you need to change these preferences to allow content to display as below.

Code

5

Now if you open website with mixed content, it will load without any issue.

Warning: Just make sure with your development team if it’s valid for application to load.

Abstract Class Vs Interface

Contract:

Often, an API is referred as a framework. We will consider a contract as an agreement that requires a developer to comply with the specification of an Application Programming Interface (API). As per English dictionary meaning of contract;


Contract

When using contracts, the developer is required to comply with the rules defined in the framework. This includes issues like method names, number of parameters, and so on. In short, standards are created to facilitate best practices for coding.

Enforcement is vital because it is always possible for a developer to breach the contract. But in the absence of a contract a rough developer could decide to reinvent the wheel and write her own code rather than use the specification provided by the framework. In Java and the .NET languages, there are two ways to implement contracts are to use abstract classes and interfaces.

Abstract Classes:

One way to implement contract is via abstract class. An abstract class is a class that contains one or more methods that do not have any implementation. Since every class is responsible for its own action but in this case there are some methods which have no implementation thus  they are abstract and that is why you cannot instantiate this class. Hence ‘abstract class cannot be instantiated’.

Let’s try to understand with an example. If I ask you to calculate an area, the first question you will be asking area of what? Circle or triangle or other. So the ‘CalculateArea’ is an abstract but area of circle or triangle not.  We can implement ‘calculateArea’ for circle and triangle separately.

We will try to understand using UML diagrams;

ContractRelationShip

This reflects the true polymorphic system. Any class using this Circle can use draw method and implement differently and get different result set.  Lets see in the form of code.

public abstract class Area {
public abstract double CaluclateArea();// no implementation for an abstract method
}

Note that this class does not provide any implementation for CaluclateArea method which makes this class abstract. There are two reasons it should be abstract, first Area does not know what kind of area I am going to calculate and;

Second, we want subclass of this base class to provide an implementation. i.e.;

public class Circle extends Area {
	double radius = 2.0;
	double PI=3.14;
@Override
public double CaluclateArea() {
	return PI*(radius * radius);
	}
}

To calculate Area of triangle you can use as follows.

public class Triangle extends Area{
	double base = 2;
	double height =4;
@Override
public double CaluclateArea() {
	return (base * height)/2;
	}
}

If you ‘extends’ Area in Circle and do not implement CalcualteArea method then code will not compile and ask you to override and implement this method.

Though the concept of an abstract class is all around abstract method, there is nothing stopping Area from actually providing some concrete methods with complete implementation. Which is common to all subclasses.  Just make sure if you have abstract methods in abstract class then you have to override and implement abstract method in a subclass. If you do not implement all abstract methods then base class should be abstract.

  • Remember

Abstract class is classified as strict inheritance, means is-a relationship works as opposed to interface  that is has-a relationship  which we will talk about  in the next topic.

Interface

I am sure you must want to ask a question that if we have abstract class that can provide the same functionality as an interface then why we need at the very first point.

Java and .NET does not provide multiple inheritance like C++. Java and .NET classes can inherit only one class so we can implement a number of interfaces.

Try to understand interface by UML diagram;

sigleRelationShip

Note that in UML diagram Nameable is identified as an interface which distinguishs it from class. It has two methods GetColor() and SetColor ().

public interface Colorable {
	String getColor();
	void(String colorName);
}

In the above code, notice that Colorable is not declared as  a class but as an interface. Thus, both methods, getColor() and setColor(), are considered abstract and there should be no implementation of any method in the interface.  You can point some difference between interface and abstract class.

  • An abstract class can have one or more abstract methods and methods with implementation while interface provides no implementation at all.
  • Subclass extends abstract class but implements the interface.
  • Subclasses have to implement all methods of interface else give compiler error while you may or may not implement all abstract methods from abstract classes.  In case if you are not implementing all method, you need to make a subclass as abstract class using abstract keyword.

Abstract class and Interface together

TBD: