I have a Java assignment in which my professor requires me to use a LeJOS NXT to make a robot that simulates a certain animal's behaviors. I chose to develop a dragon. All the possible behaviors that I've come up so far is:
Turning around if it's too close to an obstacle.
Going to sleep when battery is low.
Pushing an object if touches.
If it's too bright, find a dark spot.
etc.
I'm now quite confused because I don't know whether to develop it sequentially in one class or to split all the dragon's behaviors into different classes. Please have a look at my explanation below.
Instead of writing everything inside one class like this:
Dragon.java
public class Dragon {
LightSensor ls = new LightSensor
public static main(String args[]) {
while (!BUTTON.Escape.IsPressed()) {
if (this.closeToObject()) {
this.turnAround();
}
// more conditions
}
}
private boolean closeToObject() {
//TODO
return false;
}
private void turnAround() {
//TODO
}
//... more methods
}
However, I want to make it appears to be more object-oriented as the course is meant to help us gain more OOP skills. So what my second option is to create action classes that extends Dragon's Behavior abstract class like this (roughly):
Dragon.java
public class Dragon {
Detect detect = new Detect(); // carry all the detection methods: distance, sound, etc.
TurnAround turnAround = new TurnAround();
public static main(String args[]) {
while (!BUTTON.Escape.IsPressed()) {
if (detect.tooCloseToObject()) {
turnAround.prepare(); // beep beep alert
turnAround.setDerection(true); // e.g. turn right
turnAround.turn();
}
}
}
}
DragonBehaviors.java
abstract class DragonBehavior {
abstract void prepare();
public void setDirection(boolean direction) {
//...
}
}
TurnAround.java
public class TurnAround extends DragonBehaviors {
String direction;
public void TurnAround() {}
public void prepare() {
// sound alert
}
public void setDirection(boolean direction) {
if (direction) this.direction = "Right";
else this.direction = "Left";
}
public void turn() {
// TODO
}
}
The code above is roughly a draft, don't focus on it. Eventually, I want to ask if my idea about the OO structure above is reasonable, otherwise it's much easier to develop the whole thing in one class, but it has nothing to do with OOP. I also have several group members to make the code finished, so I think it could be better if we share the classes to develop in an OOP way.
Which way should I go in this circumstance?
I appreciate all the comments (:
Your choice of extracting different actions into classes with common super class is IMHO reasonable. However I would make Dragon class only aware of the DragonBehavior abstract class, not the subclasses. This way you can add and remove behaviours to the dragon without actually changing it.
How? Look at Chain-of-responsibility pattern - each behaviour has its place in the chain. If behaviour decides to activate itself (i.e. perform something) it may or may not allow further behaviours to be triggered. Moreover, you can and remove behaviours (even at runtime!) and rearrange them to change the precedence (is pushing the obstacle more or less important than going to sleep?).
Related
So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
What is the best design pattern to use to link these 2 interfaces? and can you possibly show me the code to do it?
The 2 interfaces:
public interface Kits {
void giveKit(Player player);
Item getIcon();
}
public interface PurchasableKits {
void giveKit(Player player);
Item getIcon(Profile profile);
}
I attempted to use the adapter pattern but it doesn't seem right because the "getIcon" method is taking in a profile as a parameter but it doesn't get used.
public class KitAdapter implements PurchasableKits {
private Kits kits;
public KitAdapter(Kits kits) {
this.kits = kits;
}
#Override
public void givetKit(Player player){
kits.giveKit(player);
}
#Override
public void getIcon(Profile profile){
kits.getIcon();
}
}
Thanks in advance
You have 1 interface PurchasableKits. A free Kit would implement the interface and call getIcon(null).
The red flag is that the 2 interfaces are almost exactly the same. No design pattern will get you out of the situation that creates.
That's a tricky question because of the rules of the inheritance and cyclic inheritance avoided in java.
I don't believe that you need to interfaces, you could do something like this:
public interface Kits {
void giveKit(Player player);
//a vargars usage
Item getIcon(Profile... p);
}
public class ConcreteClass implements Kits{
#Override
public void giveKit(Player player) {
// TODO Auto-generated method stub
}
#Override
public Item getIcon(Profile... o) {
//This is the ugly thing of this method. You must check the sent params.
//However I think it is better than send a null param, as the clean code suggest to avoid
if(o.length == 0)
System.out.println("without profile");
else
System.out.println("With profile");
return null;
}
}
public class Main {
public static void main(String[] args) {
ConcreteClass my = new ConcreteClass();
my.getIcon();
my.getIcon(new Profile());
}
}
The output:
without profile
With profile
So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
Whether or not the profile is needed in the getIcon(...) method is an implementation detail of those Kits that are purchasable. I would just have a Kit interface that has the following definition:
public interface Kit {
void giveKit(Player player);
Item getIcon(Profile profile);
}
So every time you wanted to get the icon you would pass in the Profile and it would be up to the kits that are purchasable to look at the profile. The free ones would just ignore the argument. That you sometimes pass in null and sometimes not means that you know beforehand whether or not it is free which means that something is wrong with your model.
Couple of other comments about your code. Just my opinions:
Concrete classes tend to be nouns. Interfaces tend to be verbs. Maybe KitHandler instead of Kit?
Class names tend to be singular so then you can put them in a list. Maybe Kit (or KitHandler) would be better so you can create a List<Kit> kits = ....
I used get methods to return fields which means that they typically don't take arguments. Maybe getIcon should be generateIcon(...)?
I build a game that includes moving between worlds. The main class of the program suppose to start by presenting the first world (world1 which is an instance of the firstWorldClass). It should stay in this world until a variable within the class world1 is changing (checked by world1.getMoveWorldIndicator()). Then, it should move to the next world- remove world1, build world2 and add it to the graphic view. Same from world 2 to 3.
It works fine when I do it between 2 worlds (delete all the code after add(world2)) or if I leave only the transition between the second and the third worlds. When I put both in a row it stops working (when adding the second while loop).
My code:
public class GameManager extends Program implements GameContstants{
public void init() {
world1=new firstWorldClass();
add(world1);
while(!world1.getMoveWorldIndicator()){
pause(200);
if(world1.getMoveWorldIndicator())break;
}
remove(world1);
world1=null;
world2=new secondWorldClass();
add(world2);
pause(200);
while(! world2.getMoveWorldIndicator()){
pause(200);
if(world2.getMoveWorldIndicator()) break;
}
remove(world2);
world2=null;
world3=new thirdWorldClass();
add(world3);
}
private firstWorldClass world1;
private secondWorldClass world2;
private thirdWorldClass world3;
}
I suspect that there's some kind of interaction between the while loops or a memory problem but am open to hear any idea/different way to do it.
Thanks!
I think there are lots of factors coming into play here:
Clean up your code. Keeping a few coding rules is important for bug fixing!
Don't use repetitive code over and over again. Extract to method or Class
Keep to class naming conventions => Upper camel case for classes
Don't set variables to null. Usually compilers will do that for you while optimizing. If you still feel like manually freeing up space or variable names, you should use scope brackets {} around the code instead!
Breaking down your code, we see lots of redundancies, like "getMoveWorldIndicator()" checks twice per loop, without any different effect from using it only once
I have provided a cleaner - but different - version here, to show you.
But for actually helping you with your code, we really DO NEED more of your code to gain some insight to the problem.
public class GameManager /* extends ... */{
static class WorldBase {
public boolean getMoveWorldIndicator() {
return false;
}
}
static class FirstWorld extends WorldBase {}
static class SecondWorld extends WorldBase {}
static class ThirdWorld extends WorldBase {}
public void init() {
playWorld(new FirstWorld());
playWorld(new SecondWorld());
playWorld(new ThirdWorld());
}
private void playWorld(final WorldBase pWorld) {
add(pWorld);
while (!pWorld.getMoveWorldIndicator()) {
pause(200);
}
remove(pWorld);
}
private void remove(final WorldBase pWorld1) {}
private void pause(final int pI) {}
private void add(final WorldBase pWorld1) {}
}
First off, sorry for the strange "title", but since I don't know the name, it's quite tough to describe in a short sentence.
I've been here many-many times before, however this is my first actual activity.
I usually search, read and fight my way trough what I want to know. However, I just can't seem to get to my answer this time, which I find pitty.
Lately I've read "Head First Design Patterns", which I can't recall it was covered in there. Also I've hit quite some Google terms in the box, but without the correct defenition. I just can't find the right combination of search-words to nail the answer.
I've got a question about the correct name of "forward sharing / linking"
of methods and their parameters.
I'm writing the JavaDocs comments to keep my code understandable, but I can't get the right term or Design Pattern name that fits to this.
But just asking this won't get me what I need i think. So I've got a little sample to demonstrate my question as BASIC as possible. I hope it is a bit understandable.
public class Framework()
{
private Game game = new Game();
public Framework()
{
loadComponents();
}
public void loadComponents()
{
// first loading framework requirements.. (lets say a button graphic)
game.load(); // lets start loading the game....
}
public static void main (String[] args)
{
new Framework();
}
}
public class Game()
{
private World world = new World();
public void load()
{
// now we load some of the basic graphics.. (lets say a few borders)
world.load(); // lets start loading the world!
}
}
public class World()
{
private Textures textures = new Textures();
public void load()
{
// now we load the worlds grid...
textures.load(); // ofcourse we need textures, lets load...
}
}
public class Textures()
{
public void load()
{
// loading the textures...
// end of this loading link.
}
}
In this example we started off in the Framework, called the load method in Game, then called the load method in World,
then called the load method in Textures. Lets make it a little simpler:
Framework.load()->Game.load()->World.load()->Texture.load();
But ofcourse we got more of these "links".
Framework.load()->Editor.load()->Entities.load();
Framework.input(Input input)->Game.input(Input input)->Player.input(Input input);
Framework.draw(Graphics2D g2d)->Game.draw(Graphics2D g2d)->World.draw(Graphics2D g2d);
How can I describe or call this "chaining/linking" the best? Becouse chaining in Java is like: Player.getLocation().setLocation(12,12).etc();
I hope my question is a little clear now,
thank you for your time in advance!
Edwin
I believe this is called the Delegator pattern
I am using Kmax to create a DAQ software. The philosophy of the GUI and the code is that every object on the GUI(radio buttons, check boxes, progress bars etc) has to have the same name with the relevant method. For instance an object named BUTTON is linked with the method public void BUTTON(KmaxWidget widget){code}.
My code is
import kmax.ext.*;
public class Runtime implements KmaxRuntime {
KmaxToolsheet tlsh; // Store a reference to the toolsheet environment
KmaxHist hist1D;
KmaxWidget checkBoxWidget;
public void init(KmaxToolsheet toolsheet) {
tlsh = toolsheet; // Save this reference for use in the toolsheet
hist1D = tlsh.getKmaxHist("HIST1D");
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH").setProperty("VALUE", "1");
}
public static boolean stringToBool(String s) {
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
return true;
}
public void CalibInit(KmaxWidget widget, KmaxHist histo){
histo.setUseXAxisCalibration(stringToBool(widget.getProperty("VALUE")));
histo.update();
}
public void chooseCalib(){
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
checkCalib(checkBoxWidget,hist1D);
}
public void GO(KmaxToolsheet toolsheet){}
public void SRQ(KmaxDevice device) {}
public void HALT(KmaxToolsheet toolsheet) {}
} // End of the Runtime object
In the above code I have the check box CHECK_BOX_CALIB_METH. The problem arises when someone wants to create many objects;one has to create many methods. In the above code you can see what I am trying to do. I want to create a "main" method that will do every function that is needed and then another method will apply those functions to each object.
This code compiles without any errors, but the check box isn't working. So I was thinking if there is a way around this. For instance a method that will include "submethods" that will do the job! Or perhaps a method that will construct methods in a for loop for each radio button, check box, progress bar etc. Something like
for(int i=0; i<number_of_buttons ; i++){public void BUTTON_i(){code}}
The above code may look ridiculous but I don't know what else to think and I really want to avoid having one method for each button.
Is something like that possible or is there another way around this?
EDIT
For instance I have 6 methods that do exactly the same;they just have different names.
public void SET_CALIB_1(KmaxWidget widget) {
double C0 = (getValueFrom("Ch2_1")*getValueFrom("En1_1")-getValueFrom("Ch1_1")*getValueFrom("En2_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C1 = (getValueFrom("En2_1")-getValueFrom("En1_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C2 = 0;
double[] coef = {C0, C1, C2};
hist1.setXCalibration(coef);
hist1.setUseXAxisCalibration(true);
hist1.update();
} // SET_CALIB_1
Is there a way to have a generator method to generate methods like the above?
what are the design goals for this software?
reflection may be a much better way to get access to the members; and/or put all the components into an array for access.
I find that I tend to over-engineer things a lot; since I enjoy building things; but then they get way too complicated and don't work.
so I advise to take a walk (or trudge through the snow) and think about it some more.
I have a game that tracks user stats after every match, such as how far they travelled, how many times they attacked, how far they fell, etc, and my current implementations looks somewhat as follows (simplified version):
Class Player{
int id;
public Player(){
int id = Math.random()*100000;
PlayerData.players.put(id,new PlayerData());
}
public void jump(){
//Logic to make the user jump
//...
//call the playerManager
PlayerManager.jump(this);
}
public void attack(Player target){
//logic to attack the player
//...
//call the player manager
PlayerManager.attack(this,target);
}
}
Class PlayerData{
public static HashMap<int, PlayerData> players = new HashMap<int,PlayerData>();
int id;
int timesJumped;
int timesAttacked;
}
public void incrementJumped(){
timesJumped++;
}
public void incrementAttacked(){
timesAttacked++;
}
}
Class PlayerManager{
public static void jump(Player player){
players.get(player.getId()).incrementJumped();
}
public void incrementAttacked(Player player, Player target){
players.get(player.getId()).incrementAttacked();
}
}
So I have a PlayerData class which holds all of the statistics, and brings it out of the player class because it isn't part of the player logic. Then I have PlayerManager, which would be on the server, and that controls the interactions between players (a lot of the logic that does that is excluded so I could keep this simple). I put the calls to the PlayerData class in the Manager class because sometimes you have to do certain checks between players, for instance if the attack actually hits, then you increment "attackHits".
The main problem (in my opinion, correct me if I'm wrong) is that this is not very extensible. I will have to touch the PlayerData class if I want to keep track of a new stat, by adding methods and fields, and then I have to potentially add more methods to my PlayerManager, so it isn't very modulized.
If there is an improvement to this that you would recommend, I would be very appreciative. Thanks.
I am not at all an expert in design patterns. But this is what I think might be useful:
To add actions to the player, you might wanna look at the Strategy Pattern. Just google for it and you will get lot of examples.
Here is an attempt by me:
For updating the player stats, I guess Observer Pattern will be helpful.
The Observer Pattern defines one-to-many dependency between objects so
that when one object changes state, all of its dependents are notified
and updated automatically.
It enforces loose coupling so that future changes are easy.
(You will have to read about Observer Pattern and also will have to see some examples. It is not as straight forward as Strategy.)
Due to the fact that you said you want to be able to add new stats and actions later, I would tend to make a stats object that doesn't need to know anything about the game it's recording. The advantage is that the Stats class would never need to change as you added new features.
public interface Stats {
void incrementStat(Object subject, String stat);
int getStat(Object subject, String stat);
}
You Player implementation would look something like:
public void jump() {
// Logic to make the player jump...
stats.incrementStat(this, "jump");
}
Of course, what you're trading for that flexibility is static type-checking on those increment methods. But in cases like this I tend to think the simplicity is worth it. In addition to removing tons of boiler plate from the PlayerData and PlayerManager classes, you also end up with a reusable component, and you can get rid of the cyclic dependency between PlayerManager and Player.