Tech Point Fundamentals

Friday, April 22, 2022

Design Patterns Interview Questions - Part 08

Design Patterns Interview Questions and Answers - Part 08


In Software Industry the Design Patterns and Principles are always followed. So this is the most common topic for the interview. In this article, we will see the most frequently asked 90+ Design Patterns and Principles Interview Questions with Answers

Please visit our YouTube Channel for Interviews and other videos by below link:

Please read the complete C# Interview Questions and Answers article series here.


This is the 8th part of this Design Patterns and Principles Interview Questions and Answers article series. Each part contains five Design Pattern Interview Questions. Please read all the Design Patterns and Principles Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:

Design Patterns Interview Questions - Part 08

Q57. What is Singleton Design Pattern (SDP)? What are the different types of Singleton?

Singleton pattern is the most famous Creational Pattern of GoF Design Patterns. It ensures that one and only one persistent object exists and has a single point of access to it.
The best thing about singleton is that it can be implemented lazily and can be used in the multi-threaded environment as well.

According to the GoF: "Ensure a class only has one instance, and provide a global point of access to it."

The singleton design pattern helps you to ensure that a class has one and only one instance available throughout the application runtime and provides a global way to access them.
The singleton design pattern restricts the instantiation of a class to one "single" instance that's why the name singleton. The term comes from the mathematical concept of a singleton.

Types of Singleton Pattern:

There are two forms of the singleton design pattern based on loading and instantiation and both have their own pros and cons:

1. Early or Eager Instantiation: In this type of singleton the instance is created at load time.
2. Lazy Instantiation: In this type of singleton the instance is created only when required. 

Again based on the environment singleton can be of two different flavors and both have their own advantages and disadvantages:

1. Thread-Safe Singleton: This type of singleton makes sure that one and only one instance is created in a multi-threaded environment as well.
2. Non-Thread Safe Singleton: This type of singleton does not guarantee that one and only one instance is created in a multi-threaded environment.

However, you can combine both the features i.e lazy loaded and thread-safe in a single singleton based on your requirement. Singleton is language-independent, so it is applicable to several languages C#, JAVA, C++, etc.

Component of Singleton Pattern:

Though there are various ways of implementing the singleton pattern, all of them should have the following four characteristics:

1. Sealed or Final Class: The sealed class (in C#) or final class (in Java) prevents the singleton class from inheriting or extending by any class including internal  (nested) or external classes. Please read more about the sealed class here.

2. Private Default Constructor: The private parameterless constructor prevents the singleton class from instantiation by any external class. Please read more about the private constructor here.

3. Private Static Variable: The private static variable holds the reference of the created singleton instance. The static modifier allows it to allocate memory only once.

4. Public Static Method or Property: This public static method or property provides the global point of access to the singleton object and returns the singleton instance to the caller. Please read more about the static methods and properties here.

Please read the complete singleton pattern article here for more details.

Q58. When you should use Singleton Pattern? Why Singleton Pattern is considered an Anti-Pattern?

The singleton design pattern solves the object creation problem. The singleton implementation:

  1. Singleton ensures that the singleton class has one and only one instance.
  2. Singleton controls its instantiation.
  3. Singleton restricts the number of instances.
  4. Singleton provides easy access to the sole instance of the class.

Use of Singleton:

  1. Singleton class can be used for the Dependency Injection to inject the dependent singleton object.
  2. Singleton objects are preferred over the global variables as singleton has fewer flaws compared to the global variable.
  3. Singletons are mostly used to share the common global data across the application for example logger, configuration data, database connection, etc.
  4. The factory pattern, builder pattern, and prototype patterns can also use a singleton.
  5.  Singleton is also suitable for Facade objects and service proxies. 

Why Singleton is an Anti-Pattern?

The singleton pattern is called an anti-pattern. It is also known as singletons evil or pathological liars. Some of the best-known reason behind this is as follows:

1. Only Assumption: The biggest problem with the singleton pattern is based on only an assumption. In the singleton pattern, there is an object for which there is an assumption that there will only ever be one instance at any moment. But no guideline about how it should be implemented.

2. Vague Definition: The definition of a singleton is vague in itself which causes difficulties in discussing singleton. The definition is only meaningful if it has some state, without that ensuring there is only ever one object of a particular class is meaningless.

3. SOLID's SRP Violation: The singleton design pattern also violates the Single Responsibility Principle of SOLID because it is not only responsible for the singleton's normal task but the instantiation and preventing the cloning as well. Please read more about the Single Responsibility Principle here.

4. Design Models Violation: An interface can't make any assumptions about how many objects that support that interface are needed because that issue is resolvable only in the outside world.  And singleton says that there can only ever be one object of a certain class. So the singleton underpins modularity by putting an interface and the management of its instance in one place.

5. OOP'S Encapsulation Violation: As we know the global variables have been known to be the enemy of encapsulation and singletons are basically used as global variables.

6. Unit Testing Problem: Singletons are difficult to test because they carry a global state for the duration of the program. 

Please read the complete singleton pattern article here for more details.

Q59. What is the difference between Static Class and Singleton Pattern?

  1. Both the static class and singleton class have one and only one instance throughout the whole application. 
  2. Both are used for having the global state and accessibility. 
  3. Both provide thread safety as well. 
  4. Both singleton instances and static classes cannot be garbage collected. 
  5. Both use static methods, properties, or variables for the implementation.  
  6. Both can be cloned very easily.

However, there are the following differences between them:

  1. Singleton is a pattern not a keyword like static. So for creating a static class, a static keyword is sufficient while in the case of a singleton there is a need to write the logic for the singleton.
  2. Singleton class must have a private default instance constructor while a static class cannot contain any instance constructor.
  3. A static class is neither instantiated nor extended while a singleton class can be.
  4. A static class is sealed implicitly but the singleton class must be decorated as sealed explicitly.
  5.  It is possible for a singleton to implement the interface or inherit from another class but the static class neither implements the interface nor extends from any other class.
  6. We cannot implement the dependency injection with a static class but DI is possible with the singleton class because it can be interface driven.
  7. The scope of the static class is at the app domain level because it is managed by the CLR while the scope of the singleton object is across the application lifecycle.
  8. A static class cannot have any destructor but a singleton class can define a destructor.
  9. The singleton class instance can be passed as a parameter to another method while a static class cannot be because it contains only static members.

Please read the complete singleton pattern article here and the static class article here for more details.

Q60. Is it possible to create a clone of a singleton object? How do you prevent singleton object cloning?

The whole purpose of a singleton is to control the object creation and restrict the number of objects to only one. However, the singleton object can be cloned very easily and that is a violation of the singleton pattern. 

There are two types of object cloning, shallow cloning, and deep cloning. The shallow cloning only copies the reference, not the referenced objects in the class. On the other hand, deep cloning copies the referenced objects as well

So in C# the shallow copy or clone means that value types of class are duplicated, but reference types are not. However, in deep cloning, both value types and reference types are duplicated. The MemberwiseClone() method in C# creates a shallow copy. There are multiple ways to break the singleton property of a class in Java and C#. 

1. Singleton Cloning using Clone() Method: 

In Java, the Clone() method of the Object class is used for cloning. It is a protected method and every class in Java is extended from this the Object class implicitly. So it is there for the singleton class as well. 

But for cloning the class must implement the Cloneable interface, otherwise, the Clone() method generates CloneNotSupportedException. So if you have not implemented the Cloneable interface in the Singleton class, then it does not require writing any logic to prevent cloning in the singleton. 

2. Singleton Cloning using Reflection:

Reflection is used to examine or modify the behavior of methods, classes, and interfaces at runtime. So using reflection we can create multiple objects of singleton class in Java. There are multiple ways to prevent the singleton pattern from Reflection Cloning, but one of the best solutions is to throw a run time exception in the constructor if the instance already exists. By doing so nobody would be able to create a second instance. 

One way to prevent reflection cloning is to implement the enum singleton. The reason behind this is that in Java the enum values are instantiated only once. We cannot invoke the enum constructor explicitly from the program in Java same as a static constructor in C#. JVM handles the creation and invocation of enum constructors internally.

3. Cloning using Binary Serialization:

When anyone serializes a singleton object and then again deserializes that object, it will create a new instance. Hence the deserialization violates the singleton pattern. To prevent singleton object cloning via serialization, the singleton class needs to override the readResolve() method and return the same Singleton instance from there.

Please read the complete singleton pattern article here for more details.

Q61. What is the difference between Singleton Pattern and Factory Pattern?

The singleton design pattern uses a special form of the factory design pattern to ensure that only one instance of an object is ever created. However:

  1. Singleton does not allow any parameter to be passed usually while a factory pattern allows a parameter to be passed.
  2. A singleton pattern ensures that you always get back the same instance, whereas the factory pattern generally returns a new instance of one of several possible classes depending on what parameters are actually passed by the consumer.

Please read the complete singleton pattern article here for more details.

Q62. What is Prototype Design Pattern (PDP)? When to use the Prototype Creational Design Pattern?

The Prototype Pattern is a creational design pattern that lets you copy existing objects without making your code dependent on their classes. A prototype allows us to hide the complexity of making new instances from the client. 

The concept is to copy an existing object rather than create a new instance from scratch. The existing object acts as a prototype and contains the state of the object. The newly copied object may change some properties only if required.

The Prototype pattern delegates the cloning process to the actual objects that are being cloned. The pattern declares a common interface for all objects that support cloning. This interface lets you clone an object without coupling your code to the class of that object. Usually, such an interface contains just a single clone method.

Cloning is very simple like other classes. The method creates an object of the current class and carries over all of the field values of the old object into the new one. You can even copy private fields because most programming languages let objects access private fields of other objects that belong to the same class.

An object that supports cloning is called a prototype. When your objects have dozens of fields and hundreds of possible configurations, cloning them might serve as an alternative to subclassing.

Why Prototype?

If you have an object, and you want to create an exact copy of it. How would you do it? First, you have to create a new object of the same class. Then you have to go through all the fields of the original object and copy their values over to the new object. But there is a problem here. Not all objects can be copied that way because some of the object’s fields may be private and not visible from outside of the object itself. One more problem since you have to know the object’s class to create a duplicate, your code becomes dependent on that class. 

Prototype patterns are required when object creation is a time-consuming and costly operation. Create the prototype interface and declare the clone method in it. A prototype class must define the alternative constructor that accepts an object of that class as an argument. The constructor must copy the values of all fields defined in the class from the passed object into the newly created instance. If you’re changing a subclass, you must call the parent constructor to let the superclass handle the cloning of its private fields.

Q63. What is a Fluent Interface Design Pattern? What is the use of a Fluent Interface Pattern?

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

The Fluent Interface Design Pattern falls under the category of the Creational Design Pattern. The Fluent Interfaces and Method chaining are related to each other i.e one is a concept and the other one is its implementation.

The main objective of the Fluent Interface Design Pattern is that we can apply multiple properties (or methods) to an object by connecting them with dots (.) without having to re-specify the object name each time. The Fluent interfaces simplify your object consumption code by making your code more simple, readable, and discoverable.

A fluent interface simplifies the way we use an object’s API and promotes method chaining. It is a very useful technique to make an interface of a class more expressive and easier to use for clients.

The Fluent Interface pattern is useful when you want to provide an easily readable, flowing API. Those interfaces tend to mimic domain-specific languages, so they can nearly be read as human languages. 

A fluent interface is normally implemented by using method chaining to implement method cascading, concretely by having each method return the object to which it is attached, often referred as this or self.

Method Chaining is a common technique where each method returns an object and all these methods can be chained together to form a single statement. In order to achieve this, first, we need to create a wrapper class around the Employee class as shown below.

Q64. What is the difference between Singleton Pattern and Prototype Pattern?

The prototype pattern is very unique in the creational design pattern. It does not require any class, it need only the object. While singleton requires a class to implement a singleton.
Singleton pattern deals with the object creation while the prototype pattern deals with cloning the object.

Prototype pattern allows us to create an object from the existing instance of the object while the purpose of the singleton is to ensure that one and only one instance of the class is created.

Please read the complete singleton pattern article here for more details.

To Be Continued Part-09...

Recommended Articles

Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumblerVK, and WhatsApp for regular updates.


External Reference:

  1. Wikipedia
  2. RefacturingGuru
  3. SourceMaking

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.