实现类的两种方法
当我想实现一个类时,我不知道两种类型的使用之间有什么真正的区别:(我运行并看到它们是相同的结果)
第一个示例:直接将 Renderer
实现到类。
第二个例子:创建一个子类并让这个类实现Renderer
第二个例子是我在互联网/电子书上阅读文档时经常遇到的。也许解决方案2还有更多我不知道的好处。
GLSurfaceView glView;
public class TriangleOpenGLTest implements Renderer{
public void onCreate(Bundle savedInstanceState){
glView = new GLSurfaceView(this);
glView.setRenderer(this); //this line
}
}
并且:
GLSurfaceView glView;
public class TriangleOpenGLTest implements Renderer{
public void onCreate(Bundle savedInstanceState){
glView = new GLSurfaceView(this);
glView.setRenderer(new Render() ); //And this line
}
class Render() implements Renderer{
//Override function here
}
请教我。
谢谢 :)
I don't know what real difference between two type of using when I want to implement a class: (I run and see that they are same result)
first example: implement Renderer
directly to class.
second example: create a sub-class and make this class implements Renderer
The second that I usually meet when read document on internet/ebook. Maybe solution 2 has something more benefit that I don't know.
GLSurfaceView glView;
public class TriangleOpenGLTest implements Renderer{
public void onCreate(Bundle savedInstanceState){
glView = new GLSurfaceView(this);
glView.setRenderer(this); //this line
}
}
And:
GLSurfaceView glView;
public class TriangleOpenGLTest implements Renderer{
public void onCreate(Bundle savedInstanceState){
glView = new GLSurfaceView(this);
glView.setRenderer(new Render() ); //And this line
}
class Render() implements Renderer{
//Override function here
}
Please teach me.
thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这两种方式都不错,但我更喜欢第二种方式。为什么 ?
我认为这更清楚了。这样,您就可以清楚地分离有关 Renderer 接口的特定业务代码和有关 TriangleOpenGLTest 的其他业务代码。
很容易区分什么是特定于 TriangleOpenGLTest 的,什么是特定于渲染实现的。
The two ways are good but I prefer the second way. Why ?
I think that is clearer. In that way, you separate clearly the specific business code about the Renderer interface and the other business code about your TriangleOpenGLTest.
It's easy to distinguish what is specific to the TriangleOpenGLTest and what is specific to the implementation of the rendering.
你应该努力实现高凝聚力——一个类应该做一项工作(或多或少)。
如果一个类实现了一个接口,那么该接口就是该类 API 的一部分(例如,它在其 Javadoc 中显示该类实现了该接口)。因此,您应该问自己,例如,该类是否真的是一个渲染器,并且旨在用于可以使用渲染器的任何地方?或者这只是一个实施细节?
如果它只是一个实现细节,那么最好使用另一个类(例如本地内部类,甚至匿名类),而不是泄漏 API 中的接口。
You should strive for high cohesion - a class should do one job (more or less).
If a class implements an interface then that interface is part of that class' API (e.g. it shows up in its Javadoc that the class implements the interface). So you should ask yourself e.g. is the class really a Renderer and is intended to be used everywhere a Renderer can be used? Or is it just an implemenation detail?
If it's just an implementation detail then it's better to use another class (e.g. a local inner or even an anonymous class) rather than leaking the interface in the API.