Background:
I currently have a working java application that uses WorldWind to display various types of data on a world map. The data comes from various clients via RPC. Each call is tied into a data type and has various arguments like so:
public synchronised ObjectID draw2DCircle(UUID userID, Position centre, Double radius){...}
public synchronised ObjectID draw2DRectangle(UUID userID, Position centre, Double width, Double length){...}
For every draw method there is also an update method:
public synchronised boolean update2DCircle(UUID userID, ObjectID objID, Position newCentre, Double newRadius).
Each data type has its own class so draw2DCircle has a MapSurfaceCircle class, draw2DRectangle has a MapSurfaceRectangle. There is a lot of commonality between the types and I have various interfaces for the groupings of datatypes such as 2D shapes, 3D shapes etc but the one interface that all objects have in common is the IMapObject interface that has the render, preRender, move etc calls.
The flow of operation for the draw functions is something like this:
Check function arguments.
Create MapObject.
Add MapObject to map layer (allows WorldWind to call render on it).
Update internal map that has a list of MapObjects and who owns them.
Return the ID of the MapObject to the caller.
The flow of operation for the update functions is something like this:
Check the function arguments.
Check that the caller owns the objects.
Create new Callable that will run the MapObjects updateXXX method.
Pass the callable to a FutureTask where it will then be fired off into the EDT.
Await the return via get() and return this back to the caller.
The Problem:
Normally I would not be too concerned with the setup of this but there are about 50 different types of shape that can be put on the map. That means 50 different drawXXX methods and 50 updateXXX methods each with different arguments but very similar code underneath. I have a rather large file with lots of repetitive code which is not really that great for maintainability.
My Thoughts:
I need to keep the different shape type classes so will still need to have the different constructors for each one but I think I can generalize the update calls. If I remove the specific update2DCircle, update2DRectagle etc.... in the shape classes and replace with a simple update (from the base IMapObject interface) and use varags I should be able to funnel all the RPC update calls into one method like so:
update2DCircle(Args){return shape.updateShape(Args);}
update2DRectangle(Args){return shape.updateShape(Args);}
and each shape have the implemenation:
private boolean updateShape(Object ...){}
I understand that i'm loosing type checking with the varags but the type checking is done on the RPC implementation that made the call.
Another thought I had was to not update the shape but create a new one each time the draw/update method is called but this is slightly more complicated by the fact that the shape might be changing from internal WorldWind methods (on EDT) and the RPC methods happen on a different thread so I would need some sort of shape locking.
Question:
From what I have explained, does it look like any of my proposed solutions are the correct way to do it or my existing setup was OK? Is there are better solution using some design pattern i've not thought of?
I've tried to make this as much a programming question as possible (as opposed to opinion) to meet the SO rules although I do understand how it may read but this is not my intention :)
I believe the Template method pattern is the one you should use
Related
I have come across this workaround for making custom events in java and it seems like just what I need.
Create a custom event in Java
Although, my concern is how to scale this on, lets say 20 different methods, and I also need them to be optional individually. It is known that you must override all the methods of an interface with no exceptions so at the end i would need 20 nearly similar methods to call event listeners in the exact same way. This is new stuff to me, is there any more convenient way to do this?
What I got in mind (this basically repeated 20 times):
private return_type foo(int foo1, String foo2){
//method does what it is supposed to do
//interested listeners are called, and their purpose is to execute some additional code, for this exact method
fooListener(foo1, foo2);
return something;
}
I have a ReloadableWeapon class like this:
public class ReloadableWeapon {
private int numberofbullets;
public ReloadableWeapon(int numberofbullets){
this.numberofbullets = numberofbullets;
}
public void attack(){
numberofbullets--;
}
public void reload(int reloadBullets){
this.numberofbullets += reloadBullets;
}
}
with the following interface:
public interface Command {
void execute();
}
and use it like so:
public class ReloadWeaponCommand implements Command {
private int reloadBullets;
private ReloadableWeapon weapon;
// Is is okay to specify the number of bullets?
public ReloadWeaponCommand(ReloadableWeapon weapon, int bullets){
this.weapon = weapon;
this.reloadBullets = bullets;
}
#Override
public void execute() {
weapon.reload(reloadBullets);
}
}
Client:
ReloadableWeapon chargeGun = new ReloadableWeapon(10);
Command reload = new ReloadWeaponCommand(chargeGun,10);
ReloadWeaponController controlReload = new ReloadWeaponController(reload);
controlReload.executeCommand();
I was wondering, with the command pattern, with the examples I've seen, other than the object that the command is acting on, there are no other parameters.
This example, alters the execute method to allow for a parameter.
Another example, more close to what I have here, with parameters in the constructor.
Is it bad practice/code smell to include parameters in the command pattern, in this case the constructor with the number of bullets?
I don't think adding parameters into execute will be bad design or violate command pattern.
It totally depends on how you want to use Command Object: Singleton Or Prototype scope.
If you use Prototype scope, you can pass command parameters in Constructor methods. Each command instance has its own parameters.
If you use Singleton scope (shared/reused instance), you can pass command parameters in execute method. The singleton of the command should be thread safe for this case. This solution is a friend of IoC/DI framework too.
The very purpose of this pattern is to allow to define actions, and to execute them later, once or several times.
The code you provide is a good example of this pattern : you define the action "reload", that charges the gun with an amount of bullets=10 ammunition.
Now, if you decide to modify this code to add bullets as a parameter, then you completely lose the purpose of this pattern, because you will have to define the amount of ammunition every time.
IMHO, you can keep your code as it is. You will have to define several ReloadWeaponCommand instances, with different value of bullets. Then you may have to use another pattern (such as Strategy) to switch between the commands.
Consider a case you have 95 bullets in hand in starting, and you have made 9 commands with 10 bullets and 1 command with 5 bullets. And you have submitted these commands to Invoker, now invoker doesn't have to worry about how much bullets are left. He will just execute the command. On the other hand if invoker has to provide the no of bullets at run time then it could be the case supplied number of bullets are not available.
My point here is that Invoker must not have to worry about any extra information needs to execute the command. And as mentioned in wiki "an object is used to encapsulate all information needed to perform an action or trigger an event at a later time"
Using the Command Pattern with Parameters
Consider the related 'Extension Patterns' in order to hold to a Top-Down Control paradigm 'Inversion of Control'.
This pattern, the Command Pattern, is commonly used in concert with the Composite, Iterator, and Visitor Design Patterns.
Commands are 'First Class Objects'. So it is critical that the integrity of their encapsulation is protected. Also, inverting Control From Top Down to Bottom Up, Violates a Cardinal principle of Object Oriented Design, though I see people suggesting it all of the time...
The Composite pattern will allow you to store Commands, in iterative data structures.
Before going any further, and while your code is still manageable, look at these Patterns.
There are some reasonable points made here in this thread. #Loc has it closest IMO, However, If you consider the patterns mentioned above, then, regardless of the scope of your project (it appears that you intend to make a game, no small task) you will be able to remain in control of lower-level dependency. As #Loc pointed out, with 'Dependency Injection' lower class Objects should be kept 'in the dark' when it comes to any specific implementation, in terms of the data that is consumed by them; this is (should be) reserved for the top level hierarchy. 'Programming to Interfaces, not Implementation'.
It seems that you have a notion of this. Let me just point out where I see a likely mistake at this point. Actually a couple, already, you are focused on grains of sand I.e. "Bullets" you are not at the point where trivialities like that serve any purpose, except to be a cautionary sign, that you are presently about to lose control of higher level dependencies.
Whether you are able to see it yet or not, granular parts can and should be dealt with at higher levels. I will make a couple of suggestions. #Loc already mentioned the best practice 'Constructor Injection' loosely qualified, better to maybe look up this term 'Dependency Injection'.
Take the Bullets for e.g. Since they have already appeared on your scope. The Composite Pattern is designed to deal with many differing yet related First Class Objects e.g. Commands. Between the Iterator and Visitor Patterns you are able to store all of your pre-instantiated Commands, and future instantiations as well, in a dynamic data structure, like a Linked List OR a Binary Search Tree even. At this point forget about the Strategy
Pattern, A few possible scenarios is one thing, but It makes no sense to be writing adaptive interfaces at the outset.
Another thing, I see no indication that you are spawning projectiles from a class, bullets I mean. However, even if it were just a matter of keeping track of weapon configurations, and capacities(int items) (I'm only guessing that is the cause of necessary changes in projectile counts) use a stack structure or depending on what the actual scenario is; a circular queue. If you are actually spawning projectiles from a factory, or if you decide to in the future, you are ready to take advantage of Object Pooling; which, as it turns out, was motivated by this express consideration.
Not that anyone here has done this, but I find it particularly asinine for someone to suggest that it is ok to mishandle or disregard a particular motivation behind any established (especially GoF) Design pattern. If you find yourself having to modify a GoF Design pattern, then you are using the wrong one. Just sayin'
P.S. if you absolutely must, why don't you instead, use a template solution, rather than alter an intentionally specific Interface design;
I'm building an RPG with JavaFX and need to get some advice from the experts.
What is the proper way to load certain resources? I'm not talking about images and sound, that part is easy. I'm talking about classes. For instance; I have like some odd 400+ abilities that you can activate. I have a separate class for each ability (or arte as I call them). To access this ability I want to be able to call
Data.getArte(idOfArte);
and this should return an object of type Arte. All of the artes have a separte class file.
There are other resources that are this way as well like Heroes, Enemies, and such. What would be the best way to load and call these resources for use? Is there a better way of doing this?
Edit: I'm also very concerned with performance.
A more efficient approach might be to use Entity Component System or at least borrow the composition design. This allows you to have a single concrete class, say Ability, that will contain generic fields common to all abilities, e.g. skill points cost, duration of ability, target types, activation types, etc. Then you would have a component for each special value you need to add and a control for each special behavior you need to add to that generic ability. Example:
Ability ability = new Ability();
ability.addComponent(new DurationComponent(double seconds)); // specify how long effect lasts
ability.addControl(new DamagingControl(int damage, Object targetType, etc.)); // so ability can damage
ability.addControl(new ElementAugmentingControl(Element element, Object weapon/armor, etc.)); // so ability can change status effects / elements
This should give you the idea of composition. Based on the common behavior of your abilities, you should end up with about 10-30 classes, while your 400 abilities simply become configurations of the base generic ability. To give you an example here's an RPG with roughly 100 abilities (skills) which are implemented as 6 classes. The same design can also be used with any game items / characters.
As for object creation you can do:
public static final int ABILITY_ID_SOME_NAME = 1000;
ability.addComponent(new IDComponent(ABILITY_ID_SOME_NAME));
Then each of your abilities could be a part of a global data store, where only ability prototypes are stored:
Ability ability = DataStore.getByID(ABILITY_ID_SOME_NAME).clone();
Alternatively, make the data store return an already cloned ability so that you don't expose the prototypes.
Finally, you can consider using a scripting language, e.g. javascript, to change the behavior of the generic ability. In this case all of your abilities would be stored in a folder scripts/abilities/ which you load at runtime and only the ones you need. Some arbitrary example: (heal.js file)
function onUse(object, healValue) {
if (object.hasComponent(HP_COMPONENT)) {
val hp = object.getComponent(HP_COMPONENT);
hp.value += healValue;
}
}
Here's an article that shows how to call javascript functions inside java.
You are looking for the Factory Pattern. I've found a good article about it here: http://alvinalexander.com/java/java-factory-pattern-example
I assume that you do not have to sideload class files at runtime? If that were the case I'd suggest to take a look here: Method to dynamically load java class files
So I'm working through some programming exercises in java right now and the current exercise I'm using involves using the acm.graphics library. Basic shapes and stuff drawing pictures.
What I want to do, is create a function which has parameters for a GObject and a Color object and call setFilled() and setColor appropriately (since retyping this for each shape object is extremely redundant).
The problem I'm running into is this,
The GObject class is a superclass of GRect, GOval, GLine, etc but doesn't actually contain a setFilled function (thus throwing an error when trying a parameter header such as function f(GOBject A, Color ArgC).
So how should I go about creating this function, or is it even possible without editing the standardized library for GObject. I was thinking I could deal with this error by simply creating an empty setFilled function in GObject but from what I understand its generally a bad idea to go into standardized libraries and make changes arbitrarily and the right approach for making changes should be to extend / overload from a subclass as needed. Anyways I'm at an impasse with my compiler so I'm open to ideas, thanks.
P.S/Nonrelevant Question why is the word "problem" banned from the Title Box?
Write it for the GFillable interface instead since this is implemented by the shapes you are after. http://jtf.acm.org/javadoc/complete/acm/graphics/GFillable.html
I'm looking for something similar to the Proxy pattern or the Dynamic Proxy Classes, only that I don't want to intercept method calls before they are invoked on the real object, but rather I'd like to intercept properties that are being changed. I'd like the proxy to be able to represent multiple objects with different sets of properties. Something like the Proxy class in Action Script 3 would be fine.
Here's what I want to achieve in general:
I have a thread running with an object that manages a list of values (numbers, strings, objects) which were handed over by other threads in the program, so the class can take care of creating regular persistent snapshots on disk for the purpose of checkpointing the application. This persistor object manages a "dirty" flag that signifies whether the list of values has changed since the last checkpoint and needs to lock the list while it's busy writing it to disk.
The persistor and the other components identify a particular item via a common name, so that when recovering from a crash, the other components can first check if the persistor has their latest copy saved and continue working where they left off.
During normal operation, in order to work with the objects they handed over to the persistor, I want them to receive a reference to a proxy object that looks as if it were the original one, but whenever they change some value on it, the persistor notices and acts accordingly, for example by marking the item or the list as dirty before actually setting the real value.
Edit: Alternatively, are there generic setters (like in PHP 5) in Java, that is, a method that gets called if a property doesn't exist? Or is there a type of object that I can add properties to at runtime?
If with "properties" you mean JavaBean properties, i.e. represented bay a getter and/or a setter method, then you can use a dynamic proxy to intercept the set method.
If you mean instance variables, then no can do - not on the Java level. Perhaps something could be done by manipulations on the byte code level though.
Actually, the easiest way to do it is probably by using AspectJ and defining a set() pointcut (which will intercept the field access on the byte code level).
The design pattern you are looking for is: Differential Execution. I do believe.
How does differential execution work?
Is a question I answered that deals with this.
However, may I suggest that you use a callback instead? You will have to read about this, but the general idea is that you can implement interfaces (often called listeners) that active upon "something interesting" happening. Such as having a data structure be changed.
Obligitory links:
Wiki Differential execution
Wiki Callback
Alright, here is the answer as I see it. Differential Execution is O(N) time. This is really reasonable, but if that doesn't work for ya Callbacks will. Callbacks basically work by passing a method by parameter to your class that is changing the array. This method will take the value changed and the location of the item, pass it back by parameter to the "storage class" and change the value approipriately. So, yes, you have to back each change with a method call.
I realize now this is not what you want. What it appears that you want is a way that you can supply some kind of listener on each variable in an array that would be called when that item is changed. The listener would then change the corresponding array in your "backup" to refect this change.
Natively I can't think of a way to do this. You can, of course, create your own listeners and events, using an interface. This is basically the same idea as the callbacks, though nicer to look at.
Then there is reflection... Java has reflection, and I am positive you can write something using it to do this. However, reflection is notoriously slow. Not to mention a pain to code (in my opinion).
Hope that helps...
I don't want to intercept method calls before they are invoked on the real object, but
rather I'd like to intercept properties that are being changed
So in fact, the objects you want to monitor are no convenient beans but a resurgence of C structs. The only way that comes to my mind to do that is with the Field Access call in JVMTI.
I wanted to do the same thing myself. My solution was to use dynamic proxy wrappers using Javassist. I would generate a class that implements the same interface as the class of my target object, wrap my proxy class around original class, and delegate all method calls on proxy to the original, except setters which would also fire the PropertyChangeEvent.
Anyway I posted the full explanation and the code on my blog here:
http://clockwork-fig.blogspot.com/2010/11/javabean-property-change-listener-with.html