I have a manager class that is responsible for managing Objects of a certain kind. To do so it needs to manipulate these Objects, but these Objects have no relation to the manager whatsoever, so design technically, they are in separate packages "project.managers" and "project.objects" . The important thing is that the Objects in question should only be manipulated by the managers and nowhere else, but need to be accessible by every other class in the project.
As such I'd like to have the managers have access to manipulating methods, but restrict access to every other class. The most obvious one would be to move the manager class and object class into the same package and declare manipulating methods protected, but as the managers and objects are completely separate entities they don't fit there philosophically.
(This is partly because I want my IDE to stop showing me the manipulating methods whenever I autocomplete code on the Objects in question so I always have to go the route through the manager so corresponding tables are correctly updated whenever I change the Objects in question).
Are there any ideas to that or is the obvious way the best in any case?
Why not have an interface called
ManagerFunctions
and another called
ClientFunctions
You managed objects will implement both of these.
When you create the managed objects, you pass them around, but only as references to ClientFunctions. The manager objects will, however, refer to them as ManagerFunctions and consequently have access to their 'managed' functions. The appropriate casting will simply expose the appropriate methods.
Your IDE will automatically present you wil the appropriate methods depending on how these objects are referenced.
You're asking for something akin to the "friend" declarations of C++, but there's no direct equivalent in Java - package visibility is the nearest. Alternatively you could go for a model like the XML DOM, where the methods that should be public are defined in interfaces and all client access is via these interfaces. The manager would know the concrete class of the implementation so could downcast to that as required.
As such I'd like to have the managers have access to manipulating methods, but restrict access to every other class. The most obvious one would be to move the manager class and object class into the same package and declare manipulating methods protected...
Technically, you would declare the manipulating methods package protected (no modifier at all). Protected methods allow the class to be extended easier.
but as the managers and objects are completly seperate entities they don't fit there philosophically.
I understand. Java doesn't have the "friend" declaration that C++ has.
You could comment the manipulating methods, but that doesn't solve your Eclipse problem.
Related
I am working on a Java 2D game for which I am using AWT graphics, a JFrame and a JPanel. I would like to know where I should store some non-final but globally accessible (I need to be able to read/change these variables from every other Object/Class) variables to coordinate e.g. the width and height of the game's panel, which I want to be able to change in a little settings menu within the game.
At the moment, I am storing these variables in a separate interface which most of my other classes implement, but this means I cannot change the variables as they are all final.
As I see it I have two options:
Put all these variables as static, non-final ones in my main game class and access them via Game.PanelWidth
OR
Create a separate class just for these variables and access them like this: Variables.PanelWidth, where "Variables" would be that new class' name.
Which method is better, or should I use a completely different approach?
Without going through your code, it's hard to provide a specific response.
General recommendations:
At the moment, I am storing these variables in a separate interface which most of my other classes implement, but this means I cannot change the variables as they are all final.
It's not a good idea to use inheritance to access your settings. For this reason alone I think either of the options you're considering is an improvement as it uses composition instead of inheritance.
You should consider applying the Single Responsibility Principle.
Who is responsible for managing your game's settings? Maybe a Properties object.
Who is responsible for constructing such an object? Maybe the main method.
If you apply this principle, hardly any of your classes should require access to the PanelWidth property.
Specific recommendations:
Java provides a Properties class. This class is both thread safe and easy to use when loading/storing properties to files.
From the Javadoc:
This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.
Rather than creating a static properties object, consider constructing the properties object in the main method (basically, poor-man's dependency injection)
The choice is largely up to you and should be driven by a balance between complexity and the actual needs of the application.
The interface you mentioned is a known anti-pattern Constant Interface - generally frowned upon because you litter the inheritance tree and namespace everywhere with information that should remain encapsulated. It does work though and in small projects it may be acceptable.
A separate class is a better approach, it solves at least the namespace litter. Make its constructor final to prevent accidental subclassing.
Generally, static members can work in small projects, but it can turn out to be impossible in case the project grows and it turns out that the variables aren't really application global, but only use-case global. Refactoring such a case can create a lot of work later.
Using an actual instance of the "global" settings class prevents this from the start, the cost is that you need to pass the instance around to where it needs to be accessed (e.g. as constructor parameter).
Next is threading and the issue of communicating changes to those global variables. Unless your application is running in a single thread (that would be the case in a purely event driven swing application), you cannot simply make changes to values and expect the change to take effect properly at every dependency site (imagine just having read panelWidth, but before you can read panelHeight new dimensions are set). You need a way to prevent these situations. So simple members are out. You'll want get/set methods that ensure only complete information is read and that writes of related values are atomic.
The atomicity can be ensured by encapsulating related values into a composite object, e.g.: Instead of panelWidth, panelHeight you have a panelDimension. No getters/setters for the individual values, are provided. You can only get the entire Dimension (for reads) or replace it with a new dimension (for writes). The actual member can be either volatile, of the AtomicReference variety or protected by making getter/setter synchronized.
To properly communicate changes to every dependency site, you may need some notification mechanism, so either the entire global state or individual parts of it may need the ability to register listeners and notify those listeners on changes (again threading issues are to be considered, since listener callbacks are usually implemented on the thread making the change, which may need consideration in the listener called).
I'm trying to execute the same code in every subclass of a class once the class is loaded. I need to scan the classes fields using reflection to generate an outline of the data container/class.
Is there any way to do this without invoking a method of the superclass in every subclass once it is initialized? (e.g. inheriting the static initializer of the super class)
EDIT: I'm writing a library that manages some data objects. When I want to store more data in them, I'd usually subclass them. But as this get's pretty annoying when handing them back to the library and having to cast, check instanceof all the time, I wanted to create a system of "data components", that could be added to this data objects. I want to be able to use these data components in code by directly accessing their members (not via id or string), serialize them and let the user edit them in a dynamic GUI. For generating the GUI (and for serializing) I need to know the fields of the "data component classes", that were handed to my library, but I don't want to force the main application to make a library call to register each new data component class. Therefore I'm asking if it's possible to do this automatically for each subclass of a given "data component" class, that is loaded. (without classpath scanning)
Another solution would be to just declare a getFields() method in the data component superclass which automatically scans/registers the subclass when needed, but this would add some delay (i don't know how fast/slow reflection is) on the first call when the application is not in init anymore and therefore should be running as fast as possible. (I'd like to do the scanning beforehand)
I have two classes, ImageMap, extending ImageView and PageView extending GLSurfaceView, I am using the ImageMap to mainly have hot spots on drawables but I also need to add a page flip/curl animation to it, in order to do that I need those two classes to act as one object, any idea how to do that?
It is totally clear to me that multiple inheritance is not allowed in java.
There is no way of really extend two classes. What you can do is:
You make a wrapper object, that holds one instance of each object. and simply do this.ImageMap.filed1 and so. This is more convenient while developing the class. This also allows you to proxy method invocations.
You define interfaces which should be implemented, and you make a new class which implements both. This is only for class that use this class to have the interface, without really caring about the implementation.
You may need both things, since the first is about "how to do it" and the second about "how it will be presented to objects that use it".
Your question is not about Android; it's about Java.
Java does not allow for multiple inheritance.
Your reasoning is inaccurate regarding the following:
in order to do that I need those two classes to act as one object
That's not the case. An 'Activity', for example, does not have to be an event handler; it's enough if your 'Activity' can have an event handler, e.g. as an inner class which can access the Activity's variables.
I'm using an API providing access to a special server environment. This API has a wide range of Data objects you can retrieve from it. For Example APICar
Now I'd like to have "my own" data object (MyCar) containing all information of that data object but i'd like to either leave out some properties, augment it, or simply rename some of them.
This is because i need those data objects in a JSON driven client application. So when someone changes the API mentioned above and changes names of properties my client application will break immediatly.
My question is:
Is there a best practice or a design pattern to copy objects like this? Like when you have one Object and want to transfer it into another object of another class? I've seen something like that in eclipse called "AdapterFactory" and was wondering if it's wide used thing.
To make it more clear: I have ObjectA and i need ObjectB. ObjectA comes from the API and its class can change frequently. I need a method or an Object or a Class somewhere which is capable of turning an ObjectA into ObjectB.
I think you are looking for Design Pattern Adapter
It's really just wrapping an instance of class A in an instance of class B, to provide a different way of using it / different type.
"I think" because you mention copying issues, so it may not be as much a class/type thing as a persistence / transmission thing.
Depending on your situation you may also be interested in dynamic proxying, but that's a Java feature.
What are best practices in defining access controls for methods in MVC pattern. I'm uncertain where to use static methods in a scenario like an ATM (client-server model). I'm using Java.
Appreciate if someone can shed some light on this.
Here's my approach I used to come up with a class diagram.
First I designed all the screens, sketched on a paper. (I'm kinda
artist if you wonder and into graphic design stuff :) )
Then I created View classes Created Model classes by studying the scenario
and use of data
Created Controllers for each Model and some more additional ones
Added methods to Controllers by looking at the buttons I got in the screens, which I think a straight forward way to never miss any method? + some additional ones for GUI controlling
etc.
What do you think about my approach?
Thanks.
I don't see what MVC has to do with it. A static method cannot access instance variables. Therefore static should only be used for methods that receive ALL their necessary data via parameters. Usually this is "utility" routines such as sort routines, formatters, common calculations, etc.
The other place where you might use static routines is to access static variables in a class. But it's rare that you want to do this without also accessing instance variables.
Note that there's no real requirement to make any routine static -- you can have an instance method that doesn't reference any instance variables. But a static method becomes accessible from situations where you don't have an instance handy to invoke the method.