I'm creating simple game engine in Java and I've got some packages like a:
Game
Input
Time
Graphics
Each package handles a lot of classes, most of them have (And should have) public access. Let's focus on one most important class called MouseInput.
MouseInput class handles ONLY public static methods like a getMousePosition(MouseAxis axis) {...} but it also handles some methods like a updateMousePosition() {...}.
And now I want to make this method (updateMousePosition()) callable ONLY by GameBase class that is inside Game package.
P.s. I don't want to put all those classes in one package! I want to separate them to don't make my project messy.
2th P.s. All those methods that I want to make callable only by GameBase are static.
It is possible to restrict who can call even public method by checking the call stack. This adds some code to the method receiving the call but any "wrong" calls can be rejected.
Related
I have implemented a GUI using javafx in a class called "Gui" which extends apllication. I have a seperate class which handles the logic called "Logic". I want to pass an instance of "Logic" class to to "Gui" class. Is there anyway that I can create an instance of "Gui" class before calling "Application.launch()" in main method?
Not easily, and this is almost always the wrong way to approach this. In particular, you don't even know that the main(...) method will be invoked: in Java 8 a JavaFX application is launched by the JVM without (necessarily) calling main(...) at all.
You should really consider the start(...) method in your Application subclass as the equivalent of the main(...) method in a regular Java application; in other words, think of this as your application entry point and create the Logic instance there.
I have an interface like so
public interface Manager {
public void manage();
}
Now, all Managers will need to load work to manage, however, I have mixed feelings about adding public void loadWork() to the interface...
On one hand, all Managers will do this, but on the other hand, users of a Manager class will not need to know about loadWork().
Question: Is it bad practice to add "helper" or "setup" type methods to an interface?
It's not always a bad idea to add "setup" methods in an interface. For example, Java EE has an interface called ServletContextListener that is purely meant to make setup and shut down.
It's even sometimes acceptable to make interfaces with methods you should actually never directly call such as the Runnable or the Callable interface.
Being said that, it seems is that you want to force your developers to implement a loadWork() method in Manager but you also want to hide it from the class' users.
As you say, one option is adding the method in the interface but this way the method will be accessible (which you don't want). If you don't want the method to have visibility I see two options:
Make the class Manager an abstract class and add a loadWork() protected method.
Create an interface called LoadWorker with a method loadWork(). Then create an abstract class AbstractManager that implements Manager and has as a private/protected LoadWorker field. This way, even though loadWork() is public, it's not accessible from AbstractManager's users as it is called through a protected/private field (LoadWorker).
At the end it comes to a balance between overengineering and good design. It's up to you to take the decision following the specific needs. Nevertheless, there is no 'perfect solution'.
In my app, I have MyAppResources, which will mainly contain custom styles for the app. I am thinking about what is a good way to go about applying custom styles to standard widgets, such as a CellTable, along with custom styles on the layout and custom widgets?
My question:
Since MyAppResources is a singleton (it doesn't have to be, as mentioned in other posts), but CellTableResources isn't, and CellTableResources is a member of this instance that is an interface also extending ClientBundle, will a proxy 'CellTableResources' be created on every MyAppResources.INSTANCE.cellTableResources().foo()?
If so, could I create a MyAppResources.CELLTABLE_RESOURCE_INSTANCE to get around this? Or would the creation of the proxy be negligible, even if there are plentiful calls to MyAppResources.INSTANCE.cellTableResources().#?
Secondly, more of a discussion question: what is best practice in regards to using multiple ClientBundles in this case? Should I instead use CellTableResources seperately (remove it from MyAppResources), using GWT.create(CellTableResources.class); in a widget that needs it (or using a singleton like I have for MyAppResources)?
MyAppResources:
public interface MyAppResources extends ClientBundle {
public static final MyAppResources INSTANCE = GWT.create(MyAppResources.class);
#Source("MyAppStyles.css")
public MyAppCssResource css();
public CellTableResources cellTableResources();
}
CellTableResources:
public interface CellTableResources extends CellTable.Resources {
interface CellTableStyle extends CellTable.Style {
}
#Override
#Source({ CellTable.Style.DEFAULT_CSS, "CellTableStyles.css" })
CellTableStyle cellTableStyle();
#Source("green_light.png")
ImageResource getGreenLight();
//...
}
Thank you for reading.
Multi-part question, so I'm going to try to hit this in several parts:
What is the cost of GWT.create()?
Most of the GWT class is 'magic', things that you cannot wrote for yourself in other ways, as they call on the compiler to fill in specific details for you. These are often different when running in dev mode vs compiled to JS.
In the case of GWT.create, it turns out that this is compiled out to new - it is used just to create new instances. So what is the cost of a new instance versus a singleton? This depends entirely on the object being created. If there are no fields in the object, then the cost is essentially free - in fact, the compiler may choose to actually remove the constructor call, and rewrite all later methods as static anyway!
This is what happens in most cases - GWT.create should be considered to be very cheap, unless you are doing something silly like calling it within a loop that is run many times.
What happens when I list a ClientBundle method inside another ClientBundle?
Well, what happens when you list anything inside a ClientBundle?
Anything that can be listed in a ClientBundle must be annotated with #ResourceGeneratorType, indicating how to generate that type. For example, here is ImageResource:
/**
* Provides access to image resources at runtime.
*/
#DefaultExtensions(value = {".png", ".jpg", ".gif", ".bmp"})
#ResourceGeneratorType(ImageResourceGenerator.class)
public interface ImageResource extends ResourcePrototype {
//...
It calls on ImageResourceGenerator to create images as needed. Any class described in that annotation must implement com.google.gwt.resources.ext.ResourceGenerator, which describes how to get ready to work, how to create necessary fields, how to initialize them, and how to finish up.
So what does this look like for ClientBundle itself? Check out com.google.gwt.resources.rg.BundleResourceGenerator - it is a very simple class that just calls GWT.create() on the type of the method given. So, predictable, this means that those 'child' ClientBundles are created via GWT.create, more or less the same as you might otherwise do.
Okay, what does that mean in this specific case?
It turns out that ClientBundles instances don't have fields where they track newly created objects from, but instead have static members that they use instead - effectively singletons. This means that once you have called a method once, the instance it returns will be the same instance created as the next time you call it. Two different ClientBundles with the same contents will of course then keep two different copies of the objects, but it doesn't matter how many times you create a ClientBundle - its internals will always be the same.
Anything else?
Yep! Remember that you are dealing with interfaces here, not classes, so you can actually extend more than once at once!
public interface MyAppResources extends
ClientBundle,
CellTable.Resources,
CellTree.Resources {//etc
//...
Now, if two interfaces describe the same methods you may have problems, but if not, this can provide an advantage when generated sprited images. Each individual ClientBundle will draw on its own pool of images when preparing them for use - if you have a ClientBundle within a ClientBundle, they won't work together to sprite images into bigger pieces. To get that, you need to make just one ClientBundle type. This may not matter in your particular case, but I figured it was also worth mentioning.
There is a class A that implements a method doBlah. I have a class B that subclasses A and has an #Override method doBlah. After I perform some simple manipulation in B.doBlah, I call A.doBlah.
A.doBlah calls a static method C.aStaticMethod.
A and C are part of an external library I can't modify.
Id like to have a static method CC.aStaticMethod called by A.doBlah in place of C.aStaticMethod. Would this be possible using any design patterns/hacks?
[EDIT]
I do have the source to A and I can include files from them into my code and modify etc if required. However, I cant modify the A package as such.
If you can't modify A or C, and call A directly, the answer is no.
If, on the other hand, you don't need to call A.doBlah directly, you can override it's behavior (provided the method is not final), in your own class, and have it call CC.aStaticMethod.
If you do have access to the source, you can do a very, very ugly hack:
Create a class A in exactly the same package as the original, and modify the method doBlah to call what you need.
Keep in mind that this has quite a few drawbacks, namely, if A belongs to an external library, you have NO way of knowing if an update to that library will break your code or not, since you'll be running an older version of A.
This is basically to say that this approach can turn quickly into a maintenance nightmare.
Okay, I'm NOT a Java noob, it just so happens that I've forgotten a tad bit about core Java while I was learning more fun stuff like MySQL, Servlets, Java EE, JDBC etc etc; so don't frame your answers as if I were a beginner. Now the question.....
I'm writing a class (lets say ThisIsAJFrameExtendingClass) which extends JFrame, and to minimize confusion with my overall project, I also want to park some other utility methods in ThisIsAJFrameExtendingClass. I intend this class (ThisIsAJFrameExtendingClass) to seek certain inputs from the user following which; commit suicide (ie dispose()). So, my question is, how can I independently use the utility methods inside the class without any JFrame popping up on the user screen.
I'ld like a solution with the help of multiple constructors inside the ThisIsAJFrameExtendingClass class, where, invoking the argument-less constructor return JFrame and the second constructor with a boolean argument gives access to the utility methods.
[UPDATE]
Ohh.... I just had a thought, the utility method has a return type of ArrayList so, assuming the utility method is called utilMethod() then:
ArrayList<String> pring = new ThisIsAJFrameExtendingClass().utilMethod();
will the above code output any JFrame?
You could make the utility methods static, in which case they can be invoked using ThisIsAJFrameExtendingClass.<method name> without creating an instance.
The stuff about constructors doesn't really make sense to me. A class's constructor always returns an instance of that class. It can't return "something else" because of a parameter you pass in.
[Edited to respond to the question's Update]:
new ThisIsAJFrameExtendingClass() will create an instance of your class, running its constructor (and the default constructor of all superclasses). This may allocate other resources (such as other Swing components or whatever) that each constructor in the inheritance tree requires. So a JFrame is created, but if you only call utilMethod() and never hang on to the reference to the frame, it will be garbage collected and its resources freed at some point in the future.
Creating a JFrame instance to call a single utility method on it isn't a particularly efficient way to go about things, but it won't cause any problems. (As Chad says, by default a JFrame isn't visible, so users won't see anything if you're using it in "util" mode).
As to returning an ArrayList, as a general rule when using collections, you should return the highest level interface that makes sense rather than a concrete class. So in this case, consider returning List<String> or even Collection<String>.
I have a lot of trouble getting behind your concept, which sounds a bit confused to me. At the very least, it sounds like horrible design. But I do have some suggestions:
You can make those utility methods static, then you won't need to instantiate your class at all to use them. This would be the simplest case.
You could pack your utility methods inside a static inner class of your frame, which essentially gets you around the requirement to only have one class per file.
Finally, do you just want the JFrame to disappear once the user is done with it, or do you want to terminate the application? dispose() will do only the former, your app will continue to run as a kind of headless zombie process.
Okay let's assume the methods you need aren't static.
In that case, remember the JFrame won't show up unless you call setVisible(true); So just make sure you never show the frame, and you can use whatever functions you want without it annoying the user.
Or you could design it properly and break out the utility methods into a separate class...