3

In my mobile application I need to hold a collection of File objects (pictures, documents) that can be accessed throughout the whole application and users can make various operations over the collection:

  • view all/individual files
  • upload subsets of the collection to a server
  • share individual files
  • ...

The collection is initialized only once.

I was wondering if it is a good idea to use a singleton pattern as an object that holds the collection so I do not have to initialize the collection every time user opens a particular screen?

Ondřej Z
  • 5,094
  • 3
  • 24
  • 30
  • That's definately a good idea. That way you also avoid passing references trough the varius UI classes. – das_weezul Apr 12 '11 at 10:36
  • It's probably a good idea. If you think in the future that you might want to pass only a subset of the files to a particular object, class or method, you might want to explicitly pass references to the singleton object, or its data, so that you can more easily implement the aforementioned behaviour in future. – Robin Green Apr 12 '11 at 10:44

4 Answers4

3

Absolutely, that's the purpose of the singleton pattern.

From Wikipedia, The Singleton Pattern is

useful when exactly one object is needed to coordinate actions across the system.

Example:

public class SingletonCollection {

    private Collection<File> fileCollection;
    private static SingletonCollection instance;

    private SingletonCollection() {
        fileCollection = new ArrayList<File>();
    }

    public static SingletonCollection getInstance() {
        if (instance == null) {
            instance = new SingletonCollection();
        }

        reutrn instance;
    }

    public void addFile(File f) {
        fileCollection.add(f);
    }

    public Collection<File> getFiles() {
        return fileCollection;
    }
}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
1

For Java >=1.5

public enum FileCollector
{
    INSTANCE;
    private FileCollector()
    {
        List _temp = new ArrayList();
        File f = new File("properties");
        _temp.add(f);
         fileContainer = Collections.unmodifiableList(_temp);
    }

   private final Collection<File> fileContainer;

   public Collection<File> getFiles() {
        return fileContainer;
    }

}
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112
0

If collection is initialized only once then use singleton. No doubt.

Heisenbug
  • 38,762
  • 28
  • 132
  • 190
0

If you are using Java ME try RecordStore. You can access it from anywhere in the application.

quaertym
  • 3,917
  • 2
  • 29
  • 41