Simplest Way to Hide Part of a Class' public methods/Interface - java

I am trying to design the GUI front end of a robot simulator (effectively a simple game). However, I don't know the best way of passing the simulator components (such as Robots and Walls) to the display. I want to hide the non-display oriented information of the components (such as the Robots mass), yet still be able to recognise each component im printing, i.e. when I'm drawing components I want to draw Robots differently that I do Walls (maybe the robot will have a name tag or something).
Here is a picture that will hopefully explain the design:
Maybe there is a useful design pattern that I haven't come across yet...

I think you should design this by interface contract.
I would make your walls, robots and sensors be implementations of various 'things' the UI needs to know about. Only those interfaces should be shared between the UI and your Model.
For example, Robot, Sensor should implement an interface called Printable:
public interface Printable {
Shap getShape();
}
Wall should implement an extended interface PrintableTexture
public interface PrintableTexture extends Printable {
Texture getTexture();
}
You could also create and implement data provider type interfaces for angle, direction, etc.
For example:
public interface RangeProvider {
Range getRange();
}
public interface DirectionProvider {
Direction getDirection();
}
public interface SensorProvider {
Sensor[] getSensors();
}
The main point is that the 'printing' code would then check for what interfaces are implemented by the Printable object (or list of Printable objects) that has been passed to the it and react appropriately.
Looking at your comments, I think that PrintableRobot, PrintableWall, etc is a misunderstanding of the fundamental concept of what an interface is. An interface should be more about 'what something provides or how you can use it' versus a concrete implementation of how this is achieved. By putting Robot, Wall, etc in Printable you are giving an indication of implementation.
This aside, have you considered the Visitor Pattern?? You could have each entity implement the accept part of the visitor pattern and have your printing code be a special implementation that only takes what it needs out of a deeper knowledge of what each entity does.... It's not what I would do, but it may suit you...

Checkout the model-view-controller design pattern. It separates data (robot's speed, size,...), presentation (robot's shape and its paint method) and behavior (increase robot speed).
To answer your question - the simplest way to hide parts of a class's API is to split this class into multiple pieces (model, view, controller) and connect them according to some pattern (MVC, or model-view-presenter, they are many of them).
EDIT: Sorry for that I didn't provide any example. My suggestion is just to split Robot into two classes:
RobotData (contains speed, size,... provides getters/setters, simple java bean object)
RobotUi (provides shape method (using private reference of RobotData) )
The Simulator then contains collection of RobotUi (Simulator is a model) and SimulatorDisplay (=view) iterates through the UI objects when performing paint method. The RobotData will be hidden inside RobotUi.

Related

Is there a way two tedach 2 classes that use each other's variables in Java?

I have this game I am writing in java. I've made a class called Camera, witch holds 2 static ints signifying the camera position. The camera possition is requested each frame in a lot of diffrent places. This position is also modified at times in a few diffrent places. My question is if I can detach the camera class in a way that makes the dependent classes independent and more reusable. I've looked at a few things including listeners, but I am not sure if those are meant for continous data transmision. I would really appreciate a bit of advice.
Edit:
public class Camera{
static public Vector2 cameraPosition;
static public Vector2 getCameraPosition(){
return cameraPosition;
}
}
It's also worth saying that I use a component system and I would wish to avoid passing an new camera argument to the things that need it.
Listeners should work for this usage. Use a setter of the position (including both static ints). In the setter you can call all listeners you saved in a List. Therefor make an interface for the listeners with one method (both ints are parameters). If you want to create a listener you have to implement the interface to your class and add this class to your list or just create a ‘new instance’ of this interface while adding it.
Let me know if you need a code example. But if you doesn’t know what any of this words mean, you should take a look at this parts of Java.

Trying to understand the bridge pattern

I am trying to read design patterns and currently going thru Bridge Pattern.
It states that
Decouple the functional abstraction from the implementation so that the two can vary independently
I was going thru this example on this link
:
https://www.journaldev.com/1491/bridge-design-pattern-java
Could somebody explain me how this example to this bold statement?
Thanks a lot.
Bridge is splitting the interface and implementation in multiple parts. In your example you'll get 2 different interfaces Shape, Color. They will generate their own class hierarchies and because they are independent they can both vary.
You'll end up with multiple shapes and multiple colors that can be combined at runtime. This is achieved using composition instead of inheritance. Each instance of a Shape needs an instance of a Color when it gets created and that's the way you get a red triangle or a green pentagon or any other combination of a Shape and a Color.
The hierarchies aren't tightly coupled and they only communicate at an interface level.

Use interfaces to implement pre-coded abilities

I'm making a game with different types of mobs in it. There is also a list of interfaces, each representing an ability that a mob can have. Let's say I have 100 objects extending the mob class, each one containing a different list of mob-applicable abilities (swing, explode, jump, etc.). All implementing these interfaces would do is to add blank methods to the class. If the usage of the ability is constant between all mobs, how would I make it so the ability is
pre-written so that I wouldn't need to write it again for every mob that implements it?
I do know of default methods, but they are static and don't have access to any of the mob's variables unless I pass "this" as a parameter which is something I don't want to do.
I am also aware that were there to be a solution to the problem using interfaces, those interfaces could only ever be implemented by a mob.
Thanks.
If I understand it correctly, a possible solution is to compose abilities instead of inheriting them.
interface Ability {
void doAbility();
}
class Firebending implements Ability {
private Mob mob;
public Firebending(Mob mob) {
this.mob = mob;
}
void doAbility() {
// mutate mob's state to spit fire, and attack the world
}
} // repeat this for each ability you have, flying, x-ray vision, doing taxes etc
class Mob {
private Ability[] abilities;
public Mob(Ability[] abilities) {
this.abilities = abilities;
}
}
With something like this, you can build different mobs on the fly each with a different set of abilities, suitable for when the mob varieties outnumber the number of abilities. And yes, this would involve designing your Mob class(es) to be flexible to be mutated this way.
Cool question and one I fought back and forth with. It turns out that you probably will end up in a code trap , mostly due to a strictly object oriented design approach. Having written a number of game engines I might propose an alternative thought process.
Image if you had a skeleton that needs a shield and a sword, but can at any time not have a shield, maybe you drop it, or conversely drop the sword (or both). To code this using Object Oriented design only, we would attempt to subclass from the skeleton and extend the class to have the skeleton with sword instance, but what about with shield, or with sword and shield, or both, or neither. To accomplish you could bang on it and force OOP design but as with all things, eventually the game designer will ask you to change the skeleton in some way that will cause a significant code change and you can forget about loosely coupled object sharing (say the skeleton drops the sword and the knight picks it up).
Having dealt with this and understating where you are right now, I'd suggest researching an Entity Component System.
Here the Game assets are split into Entities, Components, and Systems.
Entities: Is a simple list of integers where each integer is a component id. This allows components such as the SwordComponent to be shared across any other component. Think of an entity as a collection of components that a system can use to do some game action.
Components: A component is a simple class that ONLY contains data fields, never implementation. Each component gets a unique ID and the specific fields needed to define the component. Here I find it okay to use OOP to subclass the Component class so I really use a mix of both worlds.
System: Systems are where things get interesting. While entities are just list that combine components, and components are just data and state info, systems act on the component data to make entities work. Here you may pass in an entity and have some game logic act on the data. Systems are where you would put the code that makes each entity tick.
Here is an outline of our skeleton example:
Component[0]: Skeleton Mesh
Component[1]: Idle Animation
Component[2]: Walk Animation
Component[3]: Run Animation
Component[4]: Collision
Component[5]: Sound
Component[6]: Sword
Component[7]: Shield
Component[8]: Clown Suit
Skeleton Entity:
Entity[0] = new int {0,1,2,3,4,5,6,7,8} // Defines all the components above into one character
Possible Systems:
System[0] = Collision system handles polygon collisions, using all entities collision components.
System[1] = Animation system uses idle, walk, and run animation components and can be shared across entities.
System[2] = Render system is used to render the mesh using your render engine.
System[3] = Sound system is used to handle sound start, end, tween...
System[4] = ...
Now if the designer wants the skeleton to be able to sprout wings and fly, I don't worry about changing any previous code, I just create a new WingsComponent, add it to my entities component list, and code the new system to make the skeleton fly. Now I can freely extend my component and system pool without worrying about breaking changes.

Calling an interface method on all instances from a static method

I am not sure how to do this or if it is possible. Basically I am writing my own gui system and I want an interface to handle click detection. The gui elements (GuiButton, etc.) are all subclassess of GuiElement. What I want is to be able to statically call GuiElement.onCLick(x,y) and then have all of the child class instances of this class to fire their overwritten OnCLickListener interface.
Basically I don't want to have to keep a reference of every element and loop through it.
I assume that you are writing your own GUI as an exercise.
The comment is right, you might not want to keep a reference to all instances of GuiElement, but you have to. More than that, you probably do not want to have a static call to GuiElement.onClick(x, y). Static call like this are a code smell ... And even more, you probably do not want to propagate mouse click to all GuiElement, but only to GuiElements that are positioned at (x, y).
You should probably have a look at how MouseEvent is defined in Swing. Even if Swing has a few drawbacks, most of its base concepts are sound. Studying how it was implemented will give you a few pointer in the right direction. Writing your own GUI layer is a very good exercise, it is a very good playground to object oriented design, but some reading will help you a long way in that direction.

How to make a design "loose coupling"?

I'm making a simple 3D CAD software. in the class diagram, many objects need to distinguish with others by (x,y,z). I create a class so-called "Position", but the problem is it looks highly-coupling because many classese work with position.
Any ideas?
It is not a problem per se if a type is used by many other types. In your case, graphical objects obviously (usually) have a position so the coupling looks natural and reasonable from the perspective of the domain model.
Also, the Position class is probably going to be a fairly low-level class whose interface (and probably implementation too) is not going to change very often in the long run. So there is not much chance of such changes breaking client code.
First let me say after 12 years that your design is not bad. Assuming that the positioning logic of your classes shall be called from outside, all your classes need to have and offer this logic. So it is part of the interface and you must bring the functionalities in. And this means, you must depend on it and there is a coupling. The coupling is not between your objects. So it is not as bad.
But there are always alternatives. It is known that inheritance establishes a very tight coupling. Consider for example that the positioning logic is only called internally in your class. Then you don't have any benefit in inheritance. You could as well have another class (let us call it Position). And instead of deriving from this class, you integrate an object of this class. And whenever you want to do something with the position, you call the corresponding methods of this object.
This alternative looks like a nonsense change. Why should you do this? But let us have a look at the consequences. Assume you have a class Circle. Circle has such a position object as proposed above. (By the way, see the wording "has a position" instead of "is a position". The "object-and-composition" solution seems to be quite natural.) Somewhere in a file X of your code you may have created such a Circle. And now you decide you change the positioning logic. In X you don't have to worry that this has a side effect, because the interface of Circle has not changed. It is just one object inside of Circle that has changed. That is just an implementation detail. In contrast if you would have used inheritance, you cannot just change the base class without looking if this has a negative effect to X. So this "object-and-composition" solution has actually reduced the coupling between X and the positioning logic.
You can even reduce the coupling further. With the object-and-composition solution, whenever you change the positioning logic, you have to check all your classes if this has an effect. But what about using an interface for Position. Your classes don't see an object of a type Position, but an object that fullfils an interface Position. And the actual positioning logic implements this interface. This way most of your classes' code has no dependency to the implementation of the positioning logic.
That is not the end of the game. There is still a coupling, because your classes must somehow create the position objects. So at least the constructor must go into detail and for example pass x,y,z. But what if you use something like a factory for this purpose, so that your objects just get the position without even knowing how these have been created. Then you are absolutely flexible. You can use your classes in completely different situations. For example in a two dimensional coordinate system. There is no coupling between your positioning logic and your classes any more.
I hope you see that all these options exist. I suppose in your example this is a bit over-engineered. But your question was how to reduce the coupling. And there are always ways. Combinations are of course possible. For example you can have the object-and-composition and make the position object public in your base class. But then I would ask if not inheritance would have been the better option?

Categories