Creating a Class with a Single Instance with enum - Java Design Pattern

Java examples for Design Pattern:Singleton pattern

Introduction

First, create an enum and declare a single element named INSTANCE within it.

Next, declare other fields within the enum that you can use to store the values.

Demo Code


import java.util.ArrayList;
import java.util.List;

enum StatisticsSingleton {
  INSTANCE;//from  www  . j  a  va  2  s  .  c  o m

  private final List teams = new ArrayList();

  /**
   * @return the teams
   */
  public List getTeams() {
    return teams;
  }

  /**
   * @param teams
   *          the teams to set
   */
  public void setTeams(List teams) {
    teams = teams;
  }

}

public class Main {
  public static void main(String[] args) {
    StatisticsSingleton stats = StatisticsSingleton.INSTANCE;


    List mylist = stats.getTeams();
    mylist.add("One");
    mylist.add("Two");

    StatisticsSingleton stats2 = StatisticsSingleton.INSTANCE;
    List mylist2 = stats2.getTeams();
    for (Object name : mylist2) {
      System.out.println(name.toString());
    }

  }
}

Result


Related Tutorials