java - 如何在多个类之间共享对象

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

我怎样才能做到这一点?

最佳答案

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

另一种方法是使用接口(interface)Bundle将数据从Fragment传递到Fragment,您可以阅读有关此的更多信息 here .

关于java - 如何在多个类之间共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26703405/

相关文章:

android - 从应用程序列表中获取应用程序的 uid

android - ActionBar 进度微调器,同时将 1000 的标记添加到 android Googlemap

android - 在 Android 上获取主屏幕位置

android - 无法在 windows 7 64 位中添加 cordova android 平台?

android - 玩具VPN : unable to settup vpn server and connecting to it also no rule is appearing the nat table

java - 关闭 hibernate 连接

java - 如何使用 Maven Eclipse 和 glassfish 调试 Web 应用程序?

java - 使用 Hibernate 映射 boolean[] PostgreSql 列

Java:抽象类中的静态方法调用抽象非静态方法?

c# - Java、C++ 或 C# 中的 TPIN 号码验证