Java examples for Design Pattern:Singleton pattern
Create the class using the Singleton pattern.
import java.util.ArrayList; import java.util.List; class MyClass {/*from ww w . j av a2 s . c om*/ private static final MyClass instance = new MyClass(); private List teams = new ArrayList(); /** * Constructor has been made private so that outside classes do not have * access to instantiate more instances of Statistics. */ private MyClass() { } /** * Accessor for the statistics class. Only allows for one instance of the * class to be created. * * @return */ public static MyClass getInstance() { return instance; } /** * @return the teams */ public List getTeams() { return teams; } /** * @param teams * the teams to set */ public void setTeams(List teams) { this.teams = teams; } protected Object readResolve() { return instance; } }
Statistics Singleton that was defined in solution 1 to this recipe.
MyClass a = MyClass.getInstance(); List teams = a.getTeams();