This is used to create a class that can only have a single instance in the application.
getObject()
) from any point in the application.When you only need 1 object from a class, and want to guarantee that you can’t have more of it at once, make it a Singleton class.
Use this if you want to send data from multiple places in the app all to one location.
Use Lazy Initialization. Only instantiate the Singleton object when you first need it, not when the app is started.
Implementation
singleInstance
that points to the single instantiated object. It must be static
(because it belongs to the class), and be initialized to null
.getInstance()
that checks if there is a Singleton object, and creates one if there isn’t, then returns the object. It must be public
and static
.class Singleton
{
// Special static "single instance" field.
private static Singleton single_instance = null;
// Ordinary field variables
private String s;
// Ordinary constructor
private Singleton(String s)
{
this.s = s;
}
// Special static method. Creates and retrieves the object's data.
public static Singleton getInstance()
{
// Check if an object has been created. If not, create it.
if (single_instance == null)
single_instance = new Singleton();
return single_instance;
}
}
Caveat: This can conflict with unit tests. Might be better not to use it.
This design pattern involves organizing several similar objects under an interface or abstract class according to the action they perform, then creating a factory class with a method that creates an instance of whichever class you need.
String notificationType
).Use this design pattern when you have several objects of the same “kind”, that perform a similar function.
Implementation
// You have a notification interface, and 2 different types of notifications.
// The interface could also be an abstract class, if you want them all to use the method the same.
public interface Notification {
void notifyUser();
}
public class SMSNotification implements Notification {
@Override
public void notifyUser()
{
// TODO Auto-generated method stub
System.out.println("Sending an SMS notification");
}
}
public class EmailNotification implements Notification {
@Override
public void notifyUser()
{
// TODO Auto-generated method stub
System.out.println("Sending an e-mail notification");
}
}
// FACTORY CLASS: Used to create whichever type of notification you need.
public class NotificationFactory {
// Factory method: Takes in a string saying which Notification object to create. Then reads the string and creates the corresponding object.
public Notification createNotification(String channelType)
{
if (channelType == null || channelType.isEmpty())
return null;
else if (channelType.equals("SMS")) {
return new SMSNotification();
}
else if (channelType.equals("EMAIL")) {
return new EmailNotification();
}
return null;
}
}