Results 1 to 2 of 2
  1. #1

    Lightbulb Android Software Design Question - regarding singleton pattern

    Dear Sirs and Madams!

    In my app I have a class, which sole purpose is communicating and transferring data from/to mysql database via server side php scripts. That works ok, but now I have a demand: CDatabaseManager class (object) should be visible to all classes (objects) in application and there should be only one instance (object) of this class. How do I achieve this?

    Sincerely,
    Marko

  2. #2
    Member
    Join Date
    Jun 2011
    Location
    FL, USA
    Posts
    10

    Device(s)
    HTC G2
    You could make your database access class into a ContentProvider, although that might be overkill. ContentProviders are mainly for sharing information between multiple apps. If you only need the information within a single app, you don't need a ContentProvider...but I think you could if you wanted to.

    You could use a factory to ensure that only one instance of your database class is returned. The factory would have a static instance of your database class. All your other classes would call the factory to get access to the database.

    Here's a simple example of a factory.

    Code:
    public class CDatabaseManagerFactory {
    
    private static CDatabaseManager mDatabaseManager = null;
    
    public static CDatabaseManager getInstance() {
            if (mDatabaseManager == null) {
                mDatabaseManager = new CDatabaseManager();
            }
            return mDatabaseManager;
        }
    }
    Your other classes would make database calls by doing something like this:

    Code:
    CDatabaseManagerFactory.getInstance().doDatabaseCall()



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •