Java Design Patterns: A Hands-On Experience with Real-World Examples 2nd ed.

"IMPLEMENTATION

Here's the implementation.

package jdp2e.singleton.demo;

final class Captain{
private static Captain captain;
//We make the constructor private to prevent the use of "new"
private Captain() {    }

public static synchronized Captain getCaptain()
{
// Lazy initialization
if (captain == null)
{
captain = new Captain();
System.out.println("New captain is elected for your team.");
}
else
{
System.out.print("You already have a captain for your team.");
System.out.println("Send him for the toss.");
}
return captain;
}
}
// We cannot extend Captain class.The constructor is private in this case.
//class B extends Captain{}// error
public class SingletonPatternExample {
public static void main(String[] args) {
System.out.println("***Singleton Pattern Demo***\n");
System.out.println("Trying to make a captain for your team:");
//Constructor is private.We cannot use "new" here.
//Captain c3 = new Captain();//error
Captain captain1 = Captain.getCaptain();
System.out.println("Trying to make another captain for your team:");
Captain captain2 = Captain.getCaptain();
if (captain1 == captain2)
{
System.out.println("captain1 and captain2 are same instance.");
}
}
}" (Chapter 1)

For an Android app, this is how I implemented the singleton pattern:

package com.myapp;
..........
import android.app.Application;
..........
public class MyApplication extends Application{
static MyApplication _instance;
..........
@Override
public void onCreate() {
super.onCreate();
_instance = this;
..........
}
..........
public static MyApplication getInstance(){
return _instance;
}
..........
}


Created: 2019-08-23 21:56:03 Last updated: 2019-08-23 21:56:03

Top