2014-11-02 69 views
0

我想从类名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; 
      } 
    } 

我怎么能这样做?

+0

http://stackoverflow.com/questions/26465290/how-to-call-object-from-one-class-other/26465404#26465404 – user2717954 2014-11-02 19:33:27

回答

1

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

另一种方法是使用interfacesBundleFragment只是将数据传递到Fragment,你可以阅读更多关于这个here