简体   繁体   中英

Android: use a global object instead of creating new ones

I have a class A in my Android app where I have some methods. Those methods are public and used in other classes (B, C, D, E, F ...).

Is there a possibility to create only once the object from the class A and then use it in the other classes or i have to create new object in each classe.

Actually I have to do in each classe (B, C, D, E, F ...)

A a = new A();
a.xxxx;

It will be great if I can create only once the object a and then call it in my other classes.

thank you.

Use a singleton pattern. It allows you to use the same instance across classes:

http://www.javabeginner.com/learn-java/java-singleton-design-pattern

class A{
    static A a;
    static{
          a = new A();
    }
}

In every other class use

A.a to get the object and call respective methods as
A.a.xxxx()

Use static methods's analogy to do this.

For example:

public class Helper{
    public static void doSomething(){
        //do something here
    }
}

Now in your other classes, use the above method as below:

Helper.doSomething();

Or Singleton pattern would be an alternate too.

Instead of that why don't you make those methods static or consider single instance pattern if there are no states involved..

how to use static methods and singleton pattern

I see the following 3 possibilities:

1. If these are just "normal" helper methods you may also just do

class B extends A

and inherit the methods of A into B,C,D,E,....

2. However if you need internal memory of class A which is global to all other classes or their instances of B,C,D then may use the static pattern like

class A{

static int myGlobalIntVariable; //which is accessible from everywhere 
static void myHelperMethod1() {

}

or 3. Also you may use singleton as mentioned above which creates an instance that you use everywhere.

Just as a remark, you may use singleton or static pattern depending what you prefer when accessing the methods.

For static patter you have to call them like:

A.myHelperMethod();

and for singleton you have to do:

A.getSingleton().myHelperMethod1();  or A.singleton.myHelperMethod1()

if you have defined a variable called singleton within Class A

Which one to use really depends on your needs and taste :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM