如何在几个类之间共享对象

时间:2014-11-02 19:30:13

标签: java android

我想从类名Core创建一个新对象public Core core = new Core();并在其他类中共享它,因此每个类都可以进行更改而无需再次创建对象。

示例:

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

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

FragmentA代码:

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;
       }
    }

现在我想在课堂上检索对象:

   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;
           }
    }

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我认为其中一种方法是使用Singleton pattern,因为您始终可以在应用程序的任何部分访问数据。在您的示例中,只需将Core类设为Singleton,并始终使用getInstance()方法访问数据。

另一种方法是使用FragmentFragment将数据从interfaces传递到Bundle,您可以阅读有关此here的更多信息。