State Pattern Recipe

February 27, 2010

1.)  The basic idea of the state pattern is that you want to create an interface or an abstract class  that encapsulates several methods that have different functionality depending upon the what state the program is in.

2.)  The first thing you will want to do is draw a state diagram to figure out what possible states your program can enter and then encapsulate what varies with code.

3.) The interface or abstract class that encapsulates your methods will be the blueprint for your different types of states so you should name it state respectively.

4.) Within you state interface or abstract class you will want to set up the blueprint for how your actual states should be put together in the constructor.  Basically what you want to do is pass in an instance of whatever portion of your program that actually has the different types of states within the constructor of state.

5.)  Next you want to build the specific types of states that your program can enter.  Have your states implement or extend your state interface or abstract class respectively.   Then simply hard code the functions that you setup in your state class and construct the states with super() and your reference to the portion of your program that can enter all the different states.

6.) Last but not least you must create instances of both your state parent class and all the different state children in the portion of your program that can enter the different states and instantiate them.   You create a state variable to store states in and set its initial state.  You create instances of your different state children so that you may change the state at anytime by simply copying it into your main state variable.  Also now instead of having to worry about all that code that you put into your different state functions now all you have to do is simply say state.functionName() within your functions and it delegates the responsibility onto your state class and it delegates down to its state children.

Iterators, threads, linked lists & states.

February 25, 2010

Wow! It has been a minute since my last post, but have no fear faithful readers of the neillmorgan wordpress blog for the latest CIS 211 chronicles have arrived.  I have learned more in the past couple weeks in this class then I think I have all year.  It all started with the iterator pattern.  I read  chapter 9 in full and felt fairly competent about collections and the iterator and composite patterns.  Then lab 5 came around and let me know exactly how much I didn’t know about Linked Lists.  I think I might have been at a little disadvantage when it came to this assignment because I did not take the previous class in the sequence at UO, I took 133G at lane which is game programming with C++ and we did not cover linked lists.  I now feel like I understand singly linked lists very well but I confusion started at the head (literally).  If you check out this site here you will notice that a singly linked list can be designed in many ways as far as the way the head and tail function.  Since we weren’t shown very much in the way of linked lists in class I had no real direction while trying to design my linked list and my mind really wandered with how the head should function for what I wanted to do.  After annotating every line of the key to the linked list I got a pretty good feel for it.  Anyway,  I said I was going to resubmit my lab 5 since I didn’t do very well on it, but I my lab 6 includes the use of the linked lists and the iterator pattern so I figure that would be an exercise of utility at this point. I’m using the linked lists and iterator pattern to cycle through my animation graphics.  My linked lists consist of nodes filled with string references to the individual graphics themselves and then I use an iterator to run through them.

Another thing I learned on my ventures was threads.  I was struggling with the idea of how I was going to make my enemy characters move in the game without them moving at a million miles a minute and with an interface that wasn’t totally ridiculous.  Since I am using and abusing the draw function in my driver It would have been extremely tedious  to try and modify the way that function behaves while I’m calling it so much in my keyEvents listener that controls my main character (link).  So before I stumbled upon a solid solution to my enemy character animation problem I of course went through some trials and tribulations.  One thing I learned once and ended up learning twice is that when it comes to animation timers are not what u want.  I made a pong game in visual basic  in class a few years back and used timers to control the animation of the paddles and the ball that bounced between them.  After about 30 minutes of running the game the animation slowed to a sloth like speed and you would have to restart the program.  After a little investigation into timers and java, I came to the conclusion that they have a similar effect.  The bottom line is timers are ok if you only need one or two and you don’t depend on them for very many function calls, otherwise your processor is in bog down city.

So after investigating some source code to a few other java games I found online, I noticed they all used threads for doing animations as well as many other things.  I checked out java’s thread capabilities and was bummed to find out that to use just a basic thread you had to extend a thread class.  This was disheartening because I know I will need to eventually extend the observable class in my enemy soldier class, but  I found out that you don’t have to extend thread to use a thread.  Java provides an interface called Runnable that basically creates a giant loop that allows you to call any function you like within it and control the speed at which the thread executes with the sleep function.  So long story short, everything seems to be going well with animating my other characters in the game with threads.

To get completely up to date I added in the state pattern as lab 6 required to control the states of my enemy soldier character.  Right now he has two states, a scanning state in which he is just mulling about the room looking around for intruders and an attack state where he charges the main character if you get to close to him.  At this point it just switches once from the scanning to attack state, but eventually you will be able out run the soldier and he will resume the scanning state.  Bare with me faithful neilmorgan wordpress blog readers, I know my AI needs work, but I think what I’ve done suffices the lab 6 requirements and is a step in the right direction.  My next post will be up real soon so watch out!!  Until next time…………….. keep learning, keep coding and keep it REAL!!!

-morgan neill

Observer Pattern Pros & Cons

February 7, 2010


  • Supports the principle to strive for loosley coupled designs between objects that interact.
  • Allows you to send data to many other objects in a very efficient mannor.
  • No modification is need to be done to the subject to add new observers.
  • You can add and remove observers at anytime.


  • Java’s built in class Observable forces the use of inheritance vs programming to an interface
  • Observable protects crucial methods which means you can’t even create an instance of the Observable class and compose it with your own objects, you have to subclass.
  • If not used carefully the observer pattern can add unecessary complexity
  • The order of Observer notifications is undependable

Decorator Pattern Pros and Cons

February 7, 2010


  • Decorators provide a flexible alternative to subclassing for extending functionality
  • Decorators allow behavior modification at runtime rather than going back into existing code and making changes
  • Decorators are a nice solution to permutation issues because you can wrap a component with any number of decorators
  • The decorator pattern supports the principle that classes should be open for extension but closed for modification


  • Decorators can result in many small objects in our design, and overuse can be complex
  • Decorators can cause issues if the client relies heavily on the components concrete type
  • Decorators can complicate the process of instantiating the component because you not only have to instantiate the component but wrap it in a number of decorators
  • It can be complicated to have decorators keep track of other decorators because to look back into multiple layers of the decorator chain starts to push the decorator pattern beyond its true intent

Decorator Pattern Recipe

February 6, 2010

1.) First of all, its important to understand that the decorator pattern is a very permutation oreiented pattern.  The decorator pattern attatches additional responsibilities to an object dynamically.  So the first thing you must do when implementing the decorator pattern is figure out which of your objects are concrete (static non-changing classes) that you want to decorate(add functionality or features to) with any number of classes or permutations there of to those concrete classes.  For instance you might have a car program where you have an abstract car class that gets inherited by hatch_back, sport_car, muscle_car, and convertable classes.  Then there are all sorts of features that anyone of these car subclasses can posses such as white_wall_tires, 20_inch_rims, tinted_windows, candy_paint_job etc or any combination of the features.  Those features are what you will be decorating your concrete  hatch_back, sport_car, muscle_car, and convertable classes with.

2.)  The next thing to do is build an abstract decorator class that inherits from the same superclass that your concrete classes do.  To follow the car program example your decorator class would inherit from the car superclass.

3.) While still with in your abstract decorator class you must think about which functions that your concrete classes use to add on more functionality and you must reimplement an abstract version of those functions in your abstract decorator class. Again to follow the car program example you might want to reimplement the function that draws all your features onto your car.  This will allow your subclasses of your abstract decorator class to add more functionality to that method.

4.)  The next thing to do is build some classes that inherit from your decorator class and add functionality to your concrete classes.  To follow the car program example you would want to build your white_wall_tires, 20_inch_rims, tinted_windows, candy_paint_job feature classes and have them inherit from the decorator class.

5.) While still within your subclasses you must alter whatever method that adds functionality to your concrete classes so that it actually adds on the functionality.  Again to follow the car program example you would want to implement and alter the draw method so that it adds the whitewall tires, tinted windows etc.

6.) While still within your decorator subclasses you must make an instance of your orginal abstract class or interface that everything inherits from and make your constructor of your decorator subclasses accept a parameter of an instance of that object.  The reason for this is that you will need to call whatever method that you are altering in your decorator classes frin within that very same method in your decorator class.  To follow the car example you would need to make an instance of your orginal abstract car class within your decorator subclasses (white_wall_tires, 20_inch_rims, tinted_windows, candy_paint_job ) and create a parameter of type car within your constructor for that class.  Within your constructor you will want to copy over your car argument into your local instance of the car object.  This will give you a handle on the live car object at runtime.  Then within your draw method in your decorator subclasses you will want to call your draw method from the instance of your car superclass.

7.) Thats basically the whole structure of the decorator pattern.  The next step is to actually use it in your driver class.  To use it all you have to do is create an instance of your original superclass construct it with one of your concrete classes and then construct that same object with any number or combination of your decorator classes.  This works because both the decorator classes and the concrete classes are all inherited from the same super class.  To follow the car example you would want to do something like this:

car car1 = new hatch_back(();

car1 = new white_wall_tires(car1);

car1 = new tinted_windows(car1);

car1 = new 20_inch_rims(car1);

So now u can add any combination of features with just a constructor in your driver.  That is the whole concept of the decorator pattern.

My project so far

February 5, 2010

So far things have been going pretty smooth with the exception of a couple hiccups here and there I have no real complaints.  I’ve put in some collision detection methods into the classes of the objects that can be acted upon in the game.  Right now its just my key class that actually uses it, but soon I will have it being used all over the place by animates and inanimates alike.  The observer pattern has really come in useful in this collision detection stuff because I can have my main character being observed by the other objects like my animates and have them get updated with his coordinates and also I can have link observing the other animates in the room so he knows about there coordinates and I can then alter his movement patters so that for instance he can’t walk right through a statue or a treasure chest that I put into the room.  As far as the decorator pattern goes, I had a little trouble finding a real valid use for it.  What I ended up doing was using the decorator pattern to decorate these little blocks that I can place in the room.  I made some png graphics in gimp that simply lay red green or blue and any permutation of those colors over a block the block graphic and in turn I can make just about any color block I want.   Anyway, as a whole I feel like my project is coming along and the strategy’s are a big help.

Observer Pattern Recipe

February 1, 2010

1.) First you need to decide what objects in your program are going to be observers and which will be subjects.  Think of the Observer Pattern like a newspaper service.  The newspaper company has subscribers and delivers the paper to the subscribers.  Think about what info your observers might need from another object.

2.) To use the Observer Pattern in java there are two ways of going about it: make your own, or use java’s built in classes java.util.Observable and java.util.Observer.  There are more drawbacks to using java’s built in methods then rolling your own observer pattern.  Java’s issues include: having to subclass their Observable class, there is no Observable interface, and Observable protects crucial methods such as setChanged().

3.) Once you’ve decide which method of usage of the Observer Pattern best fits your needs all you gotta do is put it into your code.  In my game I used java’s built in methods so that is what I will be describing in the next few steps.

4.) Extend Observable in the class you want to act as your subject.  Don’t forget to include java.util.Observable, else you won’t get far.  In your method that changes your information that you want sent out to all your observers you must make two method calls that are extended from the Observer class.  First you must call setChanged() which is just basically a flag that says its ok to call the next method which you need to call directly after setChanged() and that is notifyObservers().

5.)  When calling the notifyObservers() method it is important at this point that you have decided that either your subject will send data directly to the observers (ie push data) or that your subject will simply notify the observers when it is time for them to come and get the data (ie pull data).  If you are using the push method you must include your data object that you want to update your observers with.  If you are using the pull method you will want to include other functions that will return the data you want to update your observers with.

6.)  After you have put in your setChanged() and notifyObservers() methods its time to make your observers observe =) .  In your class that you want to make an observer you must implement Observer.  Also for this class you will want to import both java.util.Observable and java.util.Observer.

7.) Once you have implemented Observer you then need to make a parameter of type Observable in the constructor for that class. This will allow you to pass in an instance of your subject as an argument.  That way your observer knows specifcally which instance of your subject to observe. Also in this class you will want to create a local observable variable to copy your subject into for later use. Don’t create it in your constuctor just put it in the class somewhere.  You want to  copy your subject into your local observable variable in the constructor.  Then to make your observer official call this line of code in your constructor: observable_var_name.addObserver(this).  That will add your class as an observer.

8.)  The last thing you need to do in your class you are making an observer is put in this method:

public void update(Observable obs, Object arg) {

//call methods from your subject to pull data

//or process and store data that is being pushed in from your data object


9.) Once you have completed all these steps you should have successfully implemented the observer pattern!

Observer Pattern Thoughts, Concerns and Issues

January 28, 2010

Well so far I’ve tried to implement the build it from scratch observer pattern.  That is I am not using the built in java features and it is not going well.  I was trying to use it for collision dectection between my main character link and other objects which is currently just a key also located in the same room.  I built some interfaces one named observer and the other named subject so that they may be implemented accordingly just like out of the book.  From there I had my link_sprite class implement the subject interface and the my key class implemented the observer interface.  In my key class I pass in an instance of my subject object(link_sprite) and register it as an observer and all my code seems to be in the right places, but I am having trouble using functions in my key class within the driver as if it never really registers itself.  Anyway, my plan is to begin refactoring tonight and next time I am going to be using the built in Java features to utilize the observer pattern, so hopefully I will have it properly moled into my game very soon.


January 19, 2010

Oliver is the observer in the book who also happens to be a cat.  He is referenced on page on the back of the third page in although the pages at that point are not numbered.

Strategy Pattern Recipe

January 19, 2010

1.)  Seperate sections of your code into 2 parts: the things that vary and those that don’t.

2.)  Place the parts that don’t vary into abstract classes.  These will become blueprints for  your classes that will envolve more detail and varied behavior.

3.)  From your abstract classes you should now extend that behavior into other classes that contain your chunks of code that vary.  In other words, you should place your chunks of code that vary into their own classes and extend your abstract class into these classes.

4.)  From here you should be able to utilize interfaces to add individualized functionality to your subclasses that were built from your abstract class.  In other words,  make some interfaces for your customized methods that you want your subclasses of your abstract class to be able to utilize.

5.)  Create some new classes that will implement your interfaces.  In other words, define your methods that your interface laid out the blueprint for.

6.)  Now that you have created your interfaces and defined methods for those interfaces in other subclasses of the interfaces you can create instance variables of those interfaces in your original abstract class.  This will allow all your subclasses of your abstract class to access their own individualized methods at run time.

7.) Before compiling your program, the last thing you have to do is go back into your subclasses of your abstract classes and instantiate your instance variables that you created in the previous step.  In other words, create constructors for your instance variables of your interfaces in your subclasses of your abstract class.  This will specifically tell your subclasses what  behaviors they should assume when their methods are called.