I'd like to hide system specific implementations from my application logic. I have chosen the following design (abstract ex开发者_Python百科ample):
public class Mesh implements Drawable {
@Override
public void draw(API api) {
api.render(this);
}
}
public class OpenGL implements API {
@Override
public void render(Drawable drawable) {
// render drawable, using OpenGL
// another API implementing class might use DirectX instead
}
}
Especially the draw(API api)
method looks odd to me because the object, the API
is passed to, will pass itself to the API
.
My (naive) questions are:
- Is this eventually a Bridge Pattern?
- Is this approach a proper implementation? (The aim is to hide system specifics.)
- Would you recommend a better approach?
It would be a Bridge Pattern if you passed the API to the constructor of Mesh. On the other hand, it looks similar to the visitor pattern.
This approach may be proper, but I cant tell that from the short snippet. A good design could look like this (which is a simple example of the visitor pattern).
- interface API
- void render(Mesh mesh);
- void render(Sprite sprite);
- interface Drawable
- void draw(API api);
- class Mesh implements Drawable
- void draw(API api) { api.render(this); }
- class Sprite implements Drawable
- void draw(API api) { api.render(this); }
- class Group implements Drawable
- void draw(API api) { for (Drawable e: elements) e.draw(api); }
In this case, this reference passing makes sense, because the implementations of Drawable select the proper (overloaded) method of the API.
Without more information, this is what I would recommend.
精彩评论