The Singleton Pattern In TypeScript

Design patterns in general, allow for developers to use pre-defined and proven templates to structure a logical solution to a type of problem.

There are a lot of design patterns available and huge books for you to read up on them. Some of these patterns can be quite confusing, while others, very intuitive, so much so that sometimes you’ll find out you’ve been implementing a pattern without even know about it.

And in particular, the Singleton pattern is probably one of the most common patterns out there, it’s not specifically complex and it’s a great way to get started with them.

What is the Singleton pattern?

The singleton pattern is a way to structure your code so that you can’t have more than one instance of your logic, ever.

In case it wasn’t obvious yet, these patterns are meant for the Object-Oriented Programming paradigm. This means that the above sentence can be translated to:

By implementing a singleton we can ensure we only have one instance of our class, ever.

As you’re about to see, Typescript has all the required tools for us to actually ensure that the above statement is 100% true.

Implementing Singleton on TypeScript

The implementation is simple, but we do have to ensure there is no way for a user to instantiate twice our class. And how can we do that? By default the new keyword creates a new instance, and we can’t override that behavior.

#design-patterns #typescript #javascript #angular #web-development

What is GEEK

Buddha Community

The Singleton Pattern In TypeScript
Seamus  Quitzon

Seamus Quitzon

1601479980

Confused With Java Singleton Design Pattern? Have a Look at This Article.

What Is a Singleton Design Pattern?

  1. Singleton design pattern allows us to create only one instance of a class and make sure that there exists only one Object in JVM.
  2. Singleton class must have a public static method to get the instance of the class from anywhere in the application [from different classes, different packages, etc].
  3. Singleton class must have a private constructor to instantiate the object of the class.
  4. Singleton class must have a private static variable of the same class which is the only reference of the class[basically this variable will point to only Object of class].

Image for post

Singleton Design Pattern

All these different implementation methods lead to one goal that is having a single instance of a class at any given point of time in JVM. Let’s see different implementation approaches for the Singleton design pattern


1. Eager Initialization :

  1. This is the simplest implementation of the singleton design pattern class. In this method, the private static variable of the same class [reference] is assigned the object of class at the time of loading the class into the JVM memory.
  2. This type of implementation is applicable to the scenarios when we always want the instance of the class.

Let’s see the program to understand this …

package com.vikram;

	public class EagerSingleton {
	    //Only object created when class is loaded and theInstance is private static var pointing to it.
	    private static EagerSingleton theInstance = new EagerSingleton();

	    //private constructor
	    private EagerSingleton(){

	    }
	    //public method to return single instance of class .
	    public static EagerSingleton getInstance(){
	        return theInstance;
	    }
	}

Eager Initialization

#desing-pattern #classloading #singleton-pattern #singleton-design-pattern #java-singleton-pattern

Samanta  Moore

Samanta Moore

1623835440

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

The Singleton Pattern In TypeScript

Design patterns in general, allow for developers to use pre-defined and proven templates to structure a logical solution to a type of problem.

There are a lot of design patterns available and huge books for you to read up on them. Some of these patterns can be quite confusing, while others, very intuitive, so much so that sometimes you’ll find out you’ve been implementing a pattern without even know about it.

And in particular, the Singleton pattern is probably one of the most common patterns out there, it’s not specifically complex and it’s a great way to get started with them.

What is the Singleton pattern?

The singleton pattern is a way to structure your code so that you can’t have more than one instance of your logic, ever.

In case it wasn’t obvious yet, these patterns are meant for the Object-Oriented Programming paradigm. This means that the above sentence can be translated to:

By implementing a singleton we can ensure we only have one instance of our class, ever.

As you’re about to see, Typescript has all the required tools for us to actually ensure that the above statement is 100% true.

Implementing Singleton on TypeScript

The implementation is simple, but we do have to ensure there is no way for a user to instantiate twice our class. And how can we do that? By default the new keyword creates a new instance, and we can’t override that behavior.

#design-patterns #typescript #javascript #angular #web-development

Nathan Agarwal

1608005169

What is the Singleton Pattern? (Software Design Patterns)

In this video, learn why the Singleton Pattern is such an important design pattern. We tell you what the
singleton pattern is, how it works, and explain it with an example.

Code: https://github.com/beabetterdevv/DesignPatterns/tree/master/patterns

Subscribe : https://www.youtube.com/channel/UCraiFqWi0qSIxXxXN4IHFBQ

#singleton #design-pattern

Why You Should Prefer Singleton Pattern over a Static Class

Introduction

After a long while, I had to create a singleton service while I’m developing a feature for the ABP Framework. Then I decided to write an article about that: Why and how should we use the singleton pattern over a static class?

OK, I agree that creating singleton class or static class, doesn’t matter, is not a good practice. However, in practical, it can be unavoidable in some points. So, which one we should prefer? While the article title already answers this question, I will explain details of this decision in this article.

While this article uses C# as the programming language, the principles can be applied in any object oriented language.

You can get the source code from my GitHub samples repository.

Using Dependency Injection?

Then you are lucky and you are doing a good thing, you can use the singleton lifetime.

ASP.NET Core allows you to register a class with the singleton lifetime. Assuming that you’ve a MyCache class and you want to register it with the singleton lifetime. Write this inside the ConfigureServices method of your Startup class and that’s all:

services.AddSingleton<MyCache>();

You still need to care about multi-threading, you shouldn’t inject transient/scoped services into your singleton service (see my dependency injection best practices guide for more), but you don’t need to manually implement the singleton pattern. ASP.NET Core Dependency Injection system handles it. Whenever you need to the MyCache service, just inject it like any other service.

However, there can be some reasons to manually implement the singleton pattern even if you use the dependency injection:

  • ASP.NET Core Dependency Injection system doesn’t allow to use services until the service registration phase completes. If you need to use your service before or inside the ConfigureServices then you can not get benefit of the dependency injection.
  • You can’t inject a service from a static context where you don’t have access to the IServiceProvider. For example, dependency injection may not be usable in an extension method.

Singleton Pattern vs Static Class

There are two main reasons that you should prefer singleton pattern over a static class. I will introduce briefly, then I will explain them in the next sections by details.

Testability

Singletons are well testable while a static class may not;

  • If your class stores state (data), running multiple tests might effect each other, so writing test will be harder.
  • Static classes are hard or impossible to mock. So, if you are testing a class depends on the static class, mocking may not be an easy option.

Extensibility

  • It is not possible to inherit from a static class, while it is possible with singleton pattern if you want to allow it. So, anyone can inherit from a singleton class, override a method and replace the service.
  • It is not possible to write an extension method to a static class while it is possible for a singleton object.

The Solution Overview

I created a solution that implements two caching services, one with the singleton pattern, the other one is a static class. I also created unit tests for both of the services:

Image for post

You can get the source code from my GitHub samples repository. The rest of the article will be based on this solution.

Implementing a Singleton Service

Let’s see a simple caching class that is implemented via the singleton pattern:

public class SingletonCache
{
    public static SingletonCache Instance { get; protected set; } = new SingletonCache();
​
    private readonly IDictionary<string, object> _cacheDictionary;

    protected internal SingletonCache()
    {
        _cacheDictionary = new Dictionary<string, object>();
    }
​
    public virtual void Add(string key, object value)
    {
        lock (_cacheDictionary)
        {
            _cacheDictionary[key] = value;
        }
    }
​
    public virtual object GetOrNull(string key)
    {
        lock (_cacheDictionary)
        {
            if (_cacheDictionary.TryGetValue(key, out object value))
            {
                return value;
            }
​
            return null;
        }
    }
​
    public virtual object GetOrAdd(string key, Func<object> factory)
    {
        lock (_cacheDictionary)
        {
            var value = GetOrNull(key);
            if (value != null)
            {
                return value;
            }
​
            value = factory();
            Add(key, value);
​
            return value;
        }
    }
​
    public virtual void Clear()
    {
        lock (_cacheDictionary)
        {
            _cacheDictionary.Clear();
        }
    }
​
    public virtual bool Remove(string key)
    {
        lock (_cacheDictionary)
        {
            return _cacheDictionary.Remove(key);
        }
    }
​
    public virtual int GetCount()
    {
        lock (_cacheDictionary)
        {
            return _cacheDictionary.Count;
        }
    }
}
  • The static Instance property is the object that should be used by other classes, like SingletonCache.Instance.Add(...) to add a new item to the cache.
  • I marked the setter as protected set to make it settable/replaceable only by a derived class.
  • The _cacheDictionary is not static because the object (Instance) is already static.
  • I declared protected internal for the constructor because;
  • protected makes possible to inherit from this class.
  • internal makes possible to create an instance of this class from the same assembly or an allowed assembly. I allowed to the SingletonVsStatic.SingletonLib.Tests project, so it can create an instance to test it (I used InternalsVisibleTo attribute in the Properties/AssemblyInfo.cs of the SingletonVsStatic.SingletonLib project to make it possible).
  • I make all methods virtual, so a derived class can override.

#aspnetcore #csharp #singleton-pattern #design-patterns #best-practices #programming-c