Which three changes should you make to apply the singleton design pattern to this class?

Given:
<code>
public class TemperatureSensor {
public TemperatureSensor () {
}
public double getCurrTemp () {
// . . . method to retrieve temperature from a sensor
Return temp;
}
</code>
Which three changes should you make to apply the singleton design pattern to this class?

Given:

public class TemperatureSensor {
public TemperatureSensor () {
}
public double getCurrTemp () {
// . . . method to retrieve temperature from a sensor
Return temp;
}

Which three changes should you make to apply the singleton design pattern to this class?

A.
Make the class abstract.

B.
Add a method to return a singleton class type.

C.
Change the access of the constructor to private.

D.
Add a public constructor that takes a single argument.

E.
Change the class to implement the singleton interface.

F.
Add a private static final variable that is initialized to new TemperatureSensor{};

G.
Add a public static method that returns the class variable of type

Explanation:
C: We provide a default Private constructor
F,G:We write a public static getter or access method(G)to get the instance of the Singleton Object
at runtime. First time the object is created inside this method as it is null. Subsequent calls to this
method returns the same object created as the object is globally declared (private)(F)and the
hence the same referenced object is returned.
Note: Java has several design patterns Singleton Pattern being the most commonly used. Java
Singleton patternbelongs to the family of design patterns, that govern the instantiation process.
This design pattern proposes that at any time there can only be one instance of a singleton
(object) created by the JVM.
The class’s default constructor is made private (C), which prevents the direct instantiation of the
object by others (Other Classes). A static modifier is applied to the instance method that returns
the object as it then makes this method a class level method that can be accessed without
creating an object.



Leave a Reply 0

Your email address will not be published. Required fields are marked *