how to ensure only one instance of singleton class is created? - singleton

I have read the concepts of Singleton design pattern and understood that for making a class singleton we have to do the following steps :
1)Private constructor to restrict instantiation of the class from other classes.
2)Private static variable of the same class that is the only instance of the class.
3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
So my class looks like this :
public class Singleton {
private static Singleton singleton =new Singleton();;
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){
System.out.println("Creating new now");
}
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
public void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
But here how we can ensure that only one instance of Singleton is created ? Suppose I have 2 classes Singletondemo1 and Singletondemo2.
In Singletondemo1 , I am calling the getInstance() and craete an object. Same way I can do that in Singletondemo2 also.
So how we will ensure only object is created and also it is thread safe.

Related

Method from mock object not being called

I have this code.
I have a real object, that is initialized with a mock object.
When I call a method from the real object that should call a method from the mock object, it doesn't call the method from the mock object, but from the base class.
Why doesn't it calls the method from the mock object, how could I fix this?
Thanks
class Parent
{
public:
virtual bool verify() const;
};
class MockParent : public Parent
{
public:
MOCK_METHOD(bool, verify, (), (const, override));
};
class MyObject
{
public:
MyObject(Parent parent) :_parent(parent) {}
Parent parent;
};
class Testclass : ::testing::Test
{
TestClass() : mockParent(), myObject(mockParent) {}
MyObject myObject;
MockParent mockParent;
};
TEST_F(Testclass , test1)
{
// here I assume that it should call the method from the mock
EXPECT_CALL(this->myObject.mockParent, verify()).WillOnce(testing::Return(true));
//call method from myObject that calls parent.verify
}
In order for the polymorphic call to trigger, you need to pass a pointer or a reference to the base class, not the base class directly:
class MyObject
{
public:
MyObject(Parent& parent) :_parent(parent) {}
private: // members are usually private
Parent& parent;
};
this will allow you to have the proper method being called. Also, please keep in mind that Parent should outlive MyObject (so that you will avoid the dangling reference error).
Some additional notes: it's best to keep a pure virtual base class:
class ParentBase
{
public:
virtual ~ParentBase() = default;
virtual bool verify() const = 0;
};
and have both Parent and ParentMock to inferit from ParentBase. This enforces better separation of concerns - your classes will then deal with interfaces, not implementations.

Cannot extend generic interface in Groovy

I am trying to implement a spring interface called the ObjectPostProcessor interface in groovy to create a new class.
I have tried to do it using a new class implementing the interface and also by creating a new anonymous class. I keep seeing an error saying.
Groovyc: Can't have an abstract method in a non-abstract class.
Which makes me think that groovy doesn't consider the abstract method of the class as overriden correctly.
Below is the code example that is breaking.
What is the correct way to implement this kind of an interface in groovy ?
interface ObjectPostProcessor<T> {
/**
* Initialize the object possibly returning a modified instance that should be used
* instead.
*
* #param object the object to initialize
* #return the initialized version of the object
*/
public <O extends T> O postProcess(O object);
}
// groovy error Error:(15, 1) Groovyc: Can't have an abstract method in a non-abstract class. The class 'ObjectPostProcessorImpl' must be declared abstract or the method 'java.lang.Object postProcess(java.lang.Object)' must be implemented.
class ObjectPostProcessorImpl implements ObjectPostProcessor<Integer> {
#Override
public <O extends Integer> O postProcess(O object) {
return object
}
}
class Anon {
public static void main(String[] args) {
ObjectPostProcessor<Integer> objectPostProcessor = new ObjectPostProcessor<Integer>() {
/** Groovyc: Can't have an abstract method in a
* non-abstract class.
* The class 'ObjectPostProcessorImpl' must
* be declared abstract or the method
* 'java.lang.Object postProcess(java.lang.Object)'
* must be implemented. */
#Override
public <O extends Integer> O postProcess(O object) {
return object;
}
};
ObjectPostProcessorImpl objectPostProcessorImplObj = new ObjectPostProcessorImpl();
System.out.println(objectPostProcessor.postProcess(12));
System.out.println(objectPostProcessorImplObj.postProcess(12));
}
}

UML class diagram relation with mother class if every child class uses the same thing

I have two questions:
I have a Singleton class with a property Layout that I use in creating child objects of an abstract class (example below). The abstract class has an abstract method where the layout file is given as a variable. Do I connect that Singleton class to the abstract class or each child? The following example is written using pseudo-code:
public class SingletonClass
{
public static Instance;
public var[,] Layout;
}
public abstract class AbstractClass
{
public abstract void DoSomething(var[,] Layout);
}
public class ClassA : AbstractClass
{
public override void DoSomething(var[,] Layout) { some code }
}
public class ClassB : AbstractClass
{
public override void DoSomething(var[,] Layout) { some other code }
}
Is it even needed, or "cleaner", to give the Layout as variable in the method, or is it ok to just call Layout from the singleton class?
The following UML is an equivalent of your code
under the following assumptions: Instance and Layout are assumed to be attributes of analogous classes.
SingletonClass has two owned attributes (denoted by the big dots): public layout of type Layout and instance of type AbstractClass (it's abstract, hence the italics). The latter will later hold either an instance of the concrete ClassA or ClassB.
Whether or not the design is ok depends. Basically there's nothing wrong with this.

Cannot create an instance for Expected Condition class in C# Selenium

When I try to create an instance for Expected Condition class it throws an error
ExpectedConditions obj = new ExpectedConditions();
The error I'm getting here is "Has no Constructors defined".
ExpectedConditions is a sealed class. And the method reside inside the sealed class are static methods.
In C# class, by default there is a constructor. Only the static classes doesn't have a default constructor.
So I have tried a small example
public sealed class A
{
public static string GetName()
{
return "name";
}
public static int GetID()
{
return 1;
}
public string Name()
{
return "aa";
}
}
//Sealed class with static methods
B obj2 = new B();
B.GetName();
B.GetID();
obj2.Name();
Build Succeeded
In my example code, It's possible to create an object for the sealed class and can be able to access the methods.
Why it is not possible to create an object with default constructor
ExpectedConditions obj = new ExpectedConditions();
for the ExpectedCondition class in C# Selenium? Why it is throwing an error when instantiating?
Some notes before:
The sealed modifier is used for a class to prevent other classes to inherit from it.
static classes do have a static constructor that is called automatically to initialize the class before the first instance is created or any static members are referenced. However, the constructor cannot be called directly. You can read more on the topic here.
Now, to get on the subject, you cannot instantiate the ExpectedConditions class because it's constructor is private. You can only use the it's static methods.
An example would be to find an element by ID and wait until it is clickable:
var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));
var clickableElement = wait.Until(ExpectedConditions.ElementIsClickable(By.Id("id")));
You can see the implementation of the ExpectedConditions class here.
Github location of the ExpectedConditions class is here.

Exists only to defeat instantiation in singleton

In many of the Singleton examples, I have come across constructor having comment as "Exists only to defeat instantiation", can you please give me details and explain more about it.
It's common to create a private constructor when implementing the Singleton pattern so that the default constructor cannot be used to instantiate multiple Singleton objects.
See the example from Wikipedia's Singleton pattern article.
public class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() { }
public static synchronized SingletonDemo getInstance() {
if (instance == null) {
instance = new SingletonDemo ();
}
return instance;
}
}
By making a private constructor, you insure that the compiler can't make a default constructor with the same signature, which forces any client code to call the getInstance() method.