创建对象的一个​​实例,并在不同的类文件中使用相同的实例 [英] Creating one instance of an object and using the same instance in different class files

查看:154
本文介绍了创建对象的一个​​实例,并在不同的类文件中使用相同的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在互联网上搜索在一个类中创建对象的实例,并在不同的类中使用同一个实例。我没有找到任何职位,但适用于我想做的。这里是我想做的一个例子。

I have been searching around the internet about Creating an instance of a object in one class and using that same instance in a different class. I have not found any posts though that apply to what I want to do. Here is an example of what I want to do.

public class ThisClass{
  public ThisClass{
    //This is the object I want to create
  }
}







public class FirstClass{
  public ThisClass thisclass = new ThisClass();
}







public class SecondClass{
  //Now in SecondClass I want to be able to access the instance of ThisClass
  //I created in FirstClass
}






在这里做什么的想法不会太复杂,噩梦看看?


Any ideas on what to do here that wont be too complex and make the code a nightmare to look at?

推荐答案

我想到了三种解决方案:

Three solutions came into my mind :


  1. Make ThisClass singleton - 以这种方式,你永远不能实例化多个类 ThisClass 类型。

  2. 创建 ThisClass 类型的实例

  3. 创建一个包含 ThisClass c>,然后在需要具有相同 ThisClass 实例的类中扩展/实现此抽象类/接口。

  1. Make ThisClass singleton - in this way you will never be able to instantiate more than one class of ThisClass type.
  2. Create an instance of ThisClass type and pass it through constructor to all other classes.
  3. Create an abstract class / interface which holds a static instance variable of type ThisClass, and then extend/implement this abstract class / interface in classes you want to have the same ThisClass instance.

这篇关于创建对象的一个​​实例,并在不同的类文件中使用相同的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆