简体   繁体   中英

How to share object between several class

I want to create one new object public Core core = new Core(); from class name Core and share it in other class, so each class can able to make change without to create again the object.

example:

public class Core {
    protected int width = 3;
    protected int hieght = 4;
    protected int calc = 0;

    public int calculate(){
        calc = width * hieght;
        return calc ;
    }
}

FragmentA code:

public class FragmentA extends Fragment {
       public Core core = new Core();
       public int resualt = core.calculate();

    private RelativeLayout        llLayout    = null;
    private FragmentActivity    faActivity  = null;
       @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           faActivity  = (FragmentActivity)    super.getActivity();


           System.out.println(" resualt: " + resualt);
           return inflater.inflate(R.layout.fragment_a,container,false);
        }

       public Core getCore(){
           return core;
       }

       public void doSomthing (){
           core.width +=1;
           core.hieght -=1;
           core.calc *=2;
       }
    }

Now I want to retrive the object in class:

   public class FragmentC extends Fragment {

        //public Core core = object  =>  here I dont know How to continu?

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_c,container,false);
        }

        public void doSomthing (){
               core.width +=2;
               core.hieght -=1;
               core.calc *=5;
           }
    }

How can I do that?

I think one of the approaches here would be usage of Singleton pattern , because you can always access data from it in any part of the application. In your example, just make a Core class a Singleton and always access data using getInstance() method.

Another way would be just passing data from Fragment to Fragment using interfaces and Bundle , you can read more about this here .

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