Using the Command Pattern with Parameters - java

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;

Related

Java Game Design Class Loading

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

Alternatives to event observer

I am building an a application that uses the event observer pattern to allow points in the system to be extended easily by 3rd party vendors who wish to add their own functionality.
This works well however it relies on 1 thing:
I must decide which points in the system vendors may wish to extend the system and trigger an event in that particular point in the flow.
It is entirely plausible that a vendor may wish to extend a different part of the system that I have not triggered an event from.
What are the alternatives here, to allow the vendor to extend the system from any point in the system they choose - or as close to that goal as possible - using something similar to event observer i.e. the can simply hook into the system where the choose to?
Okay, so you need to do two things. The first is to go out and find some real clients, and talk to them. Where do they need extensions? They know that much better than you do. The second thing is to err on the side of not providing hooks. You can always add them later, but you will have to support anything that you put out, even if it's not used.
As #Holger said, there is no way to provide arbitrary hooks to any point in your system, and it's really not desirable for you to do so. That's a maintenance nightmare.
Holger mentioned already that AOP may help you. You simply annotate your code with your custom annotations and let your customers define their own aspects (they will be required to recompile the entire code base). For example:
#Data
public class Records {
#Saving
public void add(Record rec) {
// your code
}
}
Later, your customer may say "I want to be triggered every time anyone is saving some data". He will have to define his own "aspect" with this custom "shortcut" (pseudo code):
#Aspect
public class OnSaving {
#Before("execution(* #Data #Saving(..))")
public void shortcut(JoinPoint pnt) {
// your customer's code
}
}
Your source code won't be changed, just recompiled. I assumed AspectJ usage.

Shortcut methods

My original question was quite incorrect, I have classes (not POJO), which have shortcut methods for business logic classes, to give the consumer of my API the ability to use it like:
Connector connector = new ConnectorImpl();
Entity entity = new Entity(connector);
entity.createProperty("propertyName", propertyValue);
entity.close;
Instead of:
Connector connector = new ConnectorImpl();
Entity entity = new Entity();
connector.createEntityProperty(entity, "propertyName", propertyValue);
connector.closeEntity(entity);
Is it good practice to create such shortcut methods?
Old question
At the moment I am developing a small framework and have a pretty nice separation of the business logic in different classes (connectors, authentication tokens, etc.), but one thing is still bothers me. I have methods which manipulates with POJOs, like this:
public class BuisnessLogicImpl implements BusinessLogic{
public void closeEntity(Entity entity) {
// Business Logic
}
}
And POJO entities which also have a close method:
public class Entity {
public void close(){
businessLogic.closeEntity(this);
}
}
Is it good practice to provide two ways to do the same thing? Or better, just remove all "proxy" methods from POJOs for clarity sake?
You should remove the methods from the "POJOs"... They aren't really POJO's if you encapsulate functionality like this. The reason for this comes from SOA design principles which basically says you want loose coupling between the different layers of your application.
If you are familiar with Inversion of control containers, like Google_Guice or Spring Framework-- this separation is a requirement. For instance, let's say you have a CreditCard POJO and a CreditCardProcessor service, and a DebugCreditCardProcess service that doesn't actually charge the CC money (for testing).
#Inject
private CardProcessor processor;
...
CreditCard card = new CreditCard(...params...);
processor.process(card);
In my example, I am relying on an IoC container to provide me with a CardProcessor. Whether this is the debug one, or the real one... I don't really care and neither does the CreditCard object. The one that is provided is decided by your application configuration.
If you had coupling between the processor and credit card where I could say card.process(), you would always have to pass in the processor in the card constructor. CreditCards can be used for other things besides processing however. Perhaps you just want to load a CreditCard from the database and get the expiration date... It shouldn't need a processor to do this simple operation.
You may argue: "The credit card could get the processor from a static factory". While true, singletons are widely regarded as an anti-pattern requiring keeping a global state in your application.
Keeping your business logic separate from your data model is always a good thing to do to reduce the coupling required. Loose coupling makes testing easier, and it makes your code easier to read.
I do not see your case as "two methods", because the logic of the implementation is kept in bussinessLogic. It would be akin of asking if it is a good idea java.lang.System has both a method getProperties() and a getProperty(String), more than a different method is just a shortcut to the same method.
But, in general, no, it is not good practice. Mainly because:
a) if the way to do that thing changes in the future, you need to remember that you have to touch two implementations.
b) when reading your code, other programmers will wonder if there are two methods because they are different.
Also, it does not fit very well with assigning responsabilities to a specific class for a given task, which is one of the tenets of OOP.
Of course, all absolute rules may have a special case where some considerations (mainly performance) may suggest breaking the rule. Think if you win something by doing so and document it heavily.

Correct way to use Actions to create menus, toolbars, and other components in Java

The naive way of writing building a menu in a Java Swing app is to do something like:
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open...");
openItem.addActionListener(new ActionListener() { /* action listener stuff */ } )
fileMenu.addMenuItem(openItem);
A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus, toolbar buttons, maybe even other workflows in the system. That person is more likely to write:
Action openAction = new AbstractAction();
openAction.setName("Open...");
openAction.addActionListener(new ActionListener() { /* action listener stuff */ } )
...
JMenuItem openItem = new JMenuItem(openAction);
My question is, what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?
Create a factory class that returns specific actions?
Declare all of the actions as private static final Action in some utility class?
Take advantage of a Java application framework?
Something else?
Applications that I have developed that need to use that same actions across menus, toolbars, and other buttons have been done using Swing Application Framework.
Swing Application Framework
This framework will allow you to have a resource file where you can define all menu text, tooltips, and ICONS. I think the icons are the key, you do not have to load them yourself. Also, if you have any actions that you need to enable/disable you can override the method to control its state.
The website is worth the read.
You can group all your abstractAction using the dedicated Map javax.swing.actionmap .
See http://java.sun.com/javase/6/docs/api/javax/swing/ActionMap.html
Moreover each JComponent has an internal actionMap (getActionMap()).
class MyComponent
extends JPanel
{
public static final String ACTION_NAME1="my.action.1";
public MyComponent()
{
AbstractAction action= new AbstractAction() { ... }
getActionMap().put(ACTION_NAME1,action);
...
menu.add(getActionMap().get(ACTION_NAME1));
}
}
Hope it helps
Action is a bad abstraction - an ActionListener welded to a poor man's Map.
Certainly do not assign them to a static as they are mutable and also need some context to operate usefully.
My general advice for GUI programming is to note that it is actually much the same as any other area of programming. Follow the usual good practices. Notably, layering, separation of concerns, use (implementation) inheritance rarely and don't write a big ball of mud.
Also see this question, which is pretty much the same as what you're asking.
Create a base action for your application; this will help you IMMENSELY later on
Do create actions as you have in your code, instead favor subclasses of your base action
To organize them, it will depend on what you are doing with them, and you may have some actions organized one way and others created a different way. It will all depend.
What you want is to have a consistent way to locate/create an action in your code.
Depending on your UI, you may need to differentiate between "static" actions (i.e. stuff that's always available in your app, such as the menu system) and dynamic actions that are created only on certain screens or in certain locations.
In any case, using concrete subclasses of your specialized base action will help you keep these things organized. What you don't want is to be specifying things like labels, mnemonics, and icons all over the place in your code.
Edit: I got the feeling people didn't believe this was possible or easy, so I did it--took about an hour from scratch--would have taken 40 mins if I'd just used a single method as a target instead of reflecting it out to separate methods for each menu item.
Here's the Tested source code. It works, but is one big method and ugly--refactor it if you use it. I may fix it up a little over the next few days, I've always wanted to have a copy of this to keep around to reuse.
--- original post
First of all, remember to separate your code from data. That means you should NEVER type:
new Menu("File...");
The string "File..." is data. If you start thinking this way, you will find that your question answers itself.
First you need to build up some data. You need to get "File..." and "Save" into menus. I generally start off with a string array (which you can easily move to a file)
new String[]{"File...","+Save","Load"...}
This is one of the simpler patterns I've started out with. Then you can parse out the + sign and use it to mean "Drop down a level in the menu when you add this one"
This is just a silly convention, invent your own if you don't like it.
The next step is binding that to code to run. You could have them all call the same method, but what a pain in the ass (Giant switch statement). One possibility is to use reflection to bind a method name while you are reading in the data. Here's one solution (again it might not fit your tastes)
new String[]{"File...[fileMenu]","+Save[saveMenu]","Load[loadMenu]"...}
Then you parse out the thing in square braces, reflectively hook it up to a method in your current class and you are set.
There is a temptation I ALWAYS have at this point, and I've learned to fight it because it NEVER works out. The temptation is to use the first set of data ("File...") and manipulate it to fit some pattern and auomatically bind to your code (in this case, remove all non-alpha chars, make the first letter lower case and append "Menu" to get the correct method name). Feel free to try this, it's very attractive and seems slick, but be ready to abandon it when it doesn't meet some need (such as two menu items with the exact same name in different sub-menus).
Another way would be if your language supports closures, then you could actually create the file name and closure in the same place..
Anyway, once you start coding like this, you'll find that ALL your menu construction is in a single 10 line method and you can alter it to suit your needs. I had a case where I had to change a set of menus to a button hierarchy and I did it in 2 minutes.
In the end, you can use this pattern to set up the action objects easily and change how they are used easily (in a single location, single line of code), so you experiment with them. There are many ways to use them, but if you don't do what I'm recommending here, you will end up having to re-implement across every menu item for every change, which is really annoying--after a single change you will have wasted more time than if you had just implemented a data-driven solution in the first place.
This really isn't hard code, should take like an hour or two then you never have to write new Menu("... again. Trust me, this kind of tooling is just about always worth it.
edit:
I just about always code data-driven these days. Usually I'll prototype a few things the normal way, recognize the pattern and refactor--and if you are refactoring correctly, the data just about always factors out and what you're left with is beautiful, tight and maintainable.
I could do what I suggested above in less than 1/2 an hour (maybe an hour to do the reflective version). This is almost always just as long as it would do to use the unfactored version, and from then on, your savings multiply for every change.
This is very similar to what people like about ruby, except with ruby they seem to insert even more data into their code (which makes it awfully hard to extract your data from the code completely, which is always a nice goal for internationalization).
Hmm, did I mention that if you're good at extracting your data like this, i18n is virtually free?
I suggest you just give it a try sometime and see what you think. Embedding the control in the strings is unnecessary if it makes you uncomfortable. I tend to use string/object arrays just because they are really easy to enter, are still in the file while you are coding and are trivial to externalize later, but if you like YML or XML or properties files, use whatever you're comfortable with--just abstract your data from your code!

Exposing a remote interface or object model

I have a question on the best way of exposing an asynchronous remote interface.
The conditions are as follows:
The protocol is asynchronous
A third party can modify the data at any time
The command round-trip can be significant
The model should be well suited for UI interaction
The protocol supports queries over certain objects, and so must the model
As a means of improving my lacking skills in this area (and brush up my Java in general), I have started a project to create an Eclipse-based front-end for xmms2 (described below).
So, the question is; how should I expose the remote interface as a neat data model (In this case, track management and event handling)?
I welcome anything from generic discussions to pattern name-dropping or concrete examples and patches :)
My primary goal here is learning about this class of problems in general. If my project can gain from it, fine, but I present it strictly to have something to start a discussion around.
I've implemented a protocol abstraction which I call 'client' (for legacy reasons) which allows me to access most exposed features using method calls which I am happy with even if it's far from perfect.
The features provided by the xmms2 daemon are things like track searching, meta-data retrieval and manipulation, change playback state, load playlists and so on and so forth.
I'm in the middle of updating to the latest stable release of xmms2, and I figured I might as well fix some of the glaring weaknesses of my current implementation.
My plan is to build a better abstraction on top of the protocol interface, one that allows a more natural interaction with the daemon. The current 'model' implementation is hard to use and is frankly quite ugly (not to mention the UI-code which is truly horrible atm).
Today I have the Tracks interface which I can use to get instances of Track classes based on their id. Searching is performed through the Collections interface (unfortunate namespace clash) which I'd rather move to Tracks, I think.
Any data can be modified by a third party at any time, and this should be properly reflected in the model and change-notifications distributed
These interfaces are exposed when connecting, by returning an object hierarchy that looks like this:
Connection
Playback getPlayback()
Play, pause, jump, current track etc
Expose playback state changes
Tracks getTracks()
Track getTrack(id) etc
Expose track updates
Collections getCollection()
Load and manipulate playlists or named collections
Query media library
Expose collection updates
For the asynchronous bit, I would suggest checking into java.util.concurrent, and especially the Future<T> interface. The future interface is used to represent objects which are not ready yet, but are being created in a separate thread. You say that objects can be modified at any time by a third party, but I would still suggest you use immutable return objects here, and instead have a separate thread/event log you can subscribe to to get noticed when objects expire. I have little programming with UIs, but I believe using Futures for asynchronous calls would let you have a responsive GUI, rather than one that was waiting for a server reply.
For the queries I would suggest using method chaining to build the query object, and each object returned by method chaining should be Iterable. Similar to how Djangos model is. Say you have QuerySet which implements Iterable<Song>. You can then call allSongs() which would return a result iterating over all Songs. Or allSongs().artist("Beatles"), and you would have an iterable over all Betles songs. Or even allSongs().artist("Beatles").years(1965,1967) and so on.
Hope this helps as a starting place.
Iterable only has the method Iterator get() or somesuch. So no need to build any query or execute any code until you actually start iterating. It does make the execute in your example redundant. However, the thread will be locked until the first result is available, so you might consider using an Executor to run the code for the query in a separate thread.
#Staale
It is certainly possibly, but as you note, that would make it blocking (at home for something like 10 seconds due to sleeping disks), meaning I can't use it to update the UI directly.
I could use the iterator to create a copy of the result in a separate thread and then send that to the UI, but while the iterator solution by itself is rather elegant, it won't fit in very well. In the end, something implementing IStructuredContentProvider needs to return an array of all the objects in order to display it in a TableViewer, so if I can get away with getting something like that out of a callback... :)
I'll give it some more thought. I might just be able to work out something. It does give the code a nice look.
#Staale: Thanks a bunch!
Using Future for the async operations is interesting. The only drawback being that it is doesn't provide callbacks. But then again, I tried that approach, and look where that got me :)
I'm currently solving a similar problem using a worker thread and a blocking queue for dispatching the incoming command replies, but that approach doesn't translate very well.
The remote objects can be modified, but since I do use threads, I try to keep the objects immutable. My current hypothesis is that I will send notification events on track updates on the form
somehandlername(int changes, Track old_track, Track new_track)
or similar, but then I might end up with several versions of the same track.
I'll definitely look into Djangos method chaining. I've been looking at some similar constructs but haven't been able to come up with a good variant. Returning something iterable is interesting, but the query could take some time to complete, and I wouldn't want to actually execute the query before it's completely constructed.
Perhaps something like
Tracks.allSongs().artist("Beatles").years(1965,1967).execute()
returning a Future might work...
My conclusions so far;
I am torn on whether to use getters for the Track objects or just expose the members since the object is immutable.
class Track {
public final String album;
public final String artist;
public final String title;
public final String genre;
public final String comment;
public final String cover_id;
public final long duration;
public final long bitrate;
public final long samplerate;
public final long id;
public final Date date;
/* Some more stuff here */
}
Anybody who wants to know when something happened to a track in the library would implement this...
interface TrackUpdateListener {
void trackUpdate(Track oldTrack, Track newTrack);
}
This is how querys are built. Chain calls to your hearts content. the jury is still out on the get() though. There are some details missing, such as how I should handle wildcards and more advanced queries with disjunctions. I might just need some completion callback functionality, perhaps similar to the Asynchronous Completion Token, but we'll see about that. Perhaps that will happen in an additional layer.
interface TrackQuery extends Iterable<Track> {
TrackQuery years(int from, int to);
TrackQuery artist(String name);
TrackQuery album(String name);
TrackQuery id(long id);
TrackQuery ids(long id[]);
Future<Track[]> get();
}
Some examples:
tracks.allTracks();
tracks.allTracks().artist("Front 242").album("Tyranny (For You)");
The tracks interface is mostly just the glue between the connection and the individual tracks. It will be the one implementing or managing meta-data caching, if any (as today, but I think I'll just remove it during the refactoring and see if I actually need it). Also, this provides medialib track updates as it would just be too much work to implement it by track.
interface Tracks {
TrackQuery allTracks();
void addUpdateListener(TrackUpdateListener listener);
void removeUpdateListener(TrackUpdateListener listener);
}

Categories

Resources