This lectures covers singleton design pattern.
Watch the interactive learning videos (Requires to be login). We also covered the following two concepts:
/**
* Singleton class implements singleton pattern. Only one object can be
* instantiated.
*
*/
public class Singleton {
/**
* Holds reference to single instance.
*/
private static Singleton INSTANCE;
/**
* Overrides public Constructor.
*/
private Singleton() {
}
/**
* Creates the instance if it does not yet exist(lazy instantiation).
*
* @return a reference to the single instance.
*/
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
/**
* Test implementation of the Singleton pattern.
*/
public class SingletonTest {
@Test
public void testSingleton() {
// invokes Singleton.getInstance() for first time,
// object will be created
Singleton singleton = Singleton.getInstance();
assertNotNull(singleton);
// invokes Singleton.getInstance() for second time,
// reference to the same object will be returned
Singleton secondSingleton = Singleton.getInstance();
assertEquals(singleton, secondSingleton);
}
}
Available in the diary and class teacher will have to enable it against the class.
To earn PASS status, system is about to evaluate you using multiple choice questions (MCQs) and True/False type questions.