在学校里,他们教我们在 Java 中使用 getter 和 setter。最近我一直在阅读这样的事情是不好的,而不是 OOP。好的,所以我可以编写一些代码,只使用构造函数设置数据并返回所需的数据。
你怎么不使用带线程的getter?当你执行一个线程时,它的类型总是 void 并且在 java 中有全局变量。. .. 那么如何在没有 getter 方法的情况下从线程中获取数据呢?
在学校里,他们教我们在 Java 中使用 getter 和 setter。最近我一直在阅读这样的事情是不好的,而不是 OOP。好的,所以我可以编写一些代码,只使用构造函数设置数据并返回所需的数据。
你怎么不使用带线程的getter?当你执行一个线程时,它的类型总是 void 并且在 java 中有全局变量。. .. 那么如何在没有 getter 方法的情况下从线程中获取数据呢?
最近我一直在阅读这样的事情是不好的,而不是 OOP。
恰恰相反,getter 和 setter 是 OOP 的基石之一(需要这种副作用)。
但是,您仍然可以在启动线程之前传递构造函数参数,例如,
new Thread(new MyRunnableObject(args)).start();
如果您希望它在没有getter 的情况下返回结果,您最好实现Callback
线程执行的 a,例如,在完成时。
Getter 或 setter 本身并不是糟糕的 OO 设计。
不好的是编码实践,它自动为每个成员包含一个 getter 和一个 setter,无论是否需要该 getter/setter(加上使不应该公开的成员公开) - 因为这基本上将类的实现暴露给外部世界违反信息隐藏/抽象。有时这是由 IDE 自动完成的,这意味着这种做法比预期的要广泛得多。
最近我一直在阅读这样的东西是不好的,而不是 OOP 谁说这样的废话?
Getters and Setters really are a best practice. They provide a layer for property-access so you have a single point of change when the internal workings of an accessor in a class need to be modified. You can override them in child-classes if you need to encapsulate different access strategies.
Concerning the threading:
You should use something like a threadsafe collection, I guess there are classes out there for the communication between threads. Use a threadsafe queue, which one thread writes to and the other reads from. I bet there are some good libraries for that out there. You don't really need globals. Just pass the same reference to both the classes that need to communicate across threads. You can also communicate via pipes or TCP, but that is more for inter-process communication.