Friday, March 14, 2008

Lists and Patterns

For this lab I started by constructing a simple doubly-linked list. Since we did this in Lab, it wasn't particularly hard to recreate on my own. I then tried to get a printVisitor working because while I had gotten it to work in lab, I wasn't really happy with my result and felt that it was slightly hacked together. I had better luck getting the visitor to work on my own and then embarked on getting the decorator pattern to wrap the list class with decorations for Node and Emptylist. This proved to be slightly more difficult than I had initially anticipated because of the fact that the wrappers of the Decorator pattern make it difficult to use the base wrapped classes methods because we change the class of the object to that of the wrapper. I eventually got this working, but don't really think that the decorator is a very good pattern to use with lists. I do think that it was a valid and worthwhile exercise getting it to work though, because in my project I mostly scrapped the decorator after the Lab 7 clean-your-room extravaganza.

Monday, March 3, 2008

GUI Recipe (from 3/3 lab)

1.) Create window(s)
JFrame

2.) Choose a layout

3.) Create content
Extend JPanel

4.) Add content to windows
add panels/components into frame

Friday, February 29, 2008

Visitor plus one

In this weeks assignment I added the visitor pattern and the singleton pattern to my project.

I have one Antivirus visitor that has two states (scanning and disinfecting) and visits computers and a Name visitor that visits with viruses and assigns them random names generated from several arrays and Random.nextInt().

To implement the visitor pattern, you first need to decide what objects will be the visitees and provide setters and getters for any state changes that need to be performed by the visitor. Then you have to add an acceptVisitor(Visitor v) method to each visitee class that tells the visitor v to visit it. You should create a visitor interface that has methods for visiting each class of visitee and implement this in each of your visitors. In each visitor, you must implement the methods in the visitor interface and then can perform actions on the visitee. 

Antivirus seemed like a natural place for the visitor pattern because it allowed me to simplify my project considerably. Previously I had an instance of antivirus that was 'owned' by each computer, but the visitor allowed me to pull out all that code and replace it with the acceptVisitor methods.

I used the singleton pattern in my project to ensure that only one instance my Antvirus visitor and Network class would be created because there was no need for multiple instances of them. The singleton is a very short pattern that creates an instance of the class if none exists and then returns that instance, or if it already exists, just returns it.

Wednesday, February 20, 2008

Four Patterns in Concert

For assignment 6, I decided to model a class of 4 students and a lecturing professor. The students observe the professor, who has 2 states: OnTopicState and OnTangentState.

When the professor is on topic, the students use the strategy pattern to set their listen() behavior to AttentiveStrategy and uses a System.out.println to print what the student is doing (taking notes, listening, or distracted).

When the professor is on a tangent, the students have their listen() behavior set to SpaceOutStrategy which can make the student print out that they are sleeping, doodling, browsing the internet, daydreaming, or paying attention and amused.

The students are decorated with Freshman, Sophomore, Junior, and Senior, which have info() methods that return a String with the students name and class.

A standard class period in my program is 50 minutes long and the professor will pick a random amount of time between 1 and 25 minutes to either be on topic or on a tangent before the state is switched. When the class timer reaches 0, the class is dismissed and the students leave.

I decided that my console output was pretty boring when I finished implementing the patterns, so I added String arrays so that the teacher would lecture on different topics and go on tangent about different things similar to how I made the students have several options for their listen() behaviors.

I had a lot of fun with this project and feel like I can now go back to my more complicated project with a better idea of how to compose patterns and not let all the details obscure the implementation. 

Friday, February 15, 2008

State Pattern Ideas

I haven't implemented my state pattern yet, but I'm planning on retooling the way that my Computer class stores whether or not it is infected. I'm going to add states for being infected, clean, or hosed by a virus. The other place I will add the state pattern will be my Virus classes. I would like my viruses to have states for Seeking computers to infect, infecting a computer, and hiding from antivirus.

State Pattern Recipe

You'll first need to determine the object(s) you'd like to apply the state pattern to and what states and transitions will be needed. Use a state diagram like the one in Head First Design Patterns if you want to visualize this properly.

1.) Create a State interface
2.) Write methods for the state transitions
3.) Create a class that implements State and add the state methods as specified in the interface
4.) in each state change method, you can use if/else statements to check the current state and offer different responses based on what state the object is currently in
5.) Create instance variables of type State for all your states and for the current state, which should be assigned to the state that the object should start in
6.) create a setter method that lets you set the state and a getter method so that you can get the current state

You now have a sort of rudimentary AI that can do different behaviors based on the current state.

Friday, February 8, 2008

Decorator Pattern Recipe

1.) Figure out which decorations/wrappers you'll need
2.) Create an abstract Decorator class that extends the superclass of the objects you wish to decorate
3.) Create wrapper classes that extend the decorator class. The constructor should take a reference to the object the class is to wrap so that you can use the methods in all layers of the decorated classes
4.) Define any methods from the abstract class
5.) To wrap an object up in a decorator, all you have to do it assign it to your decorator and pass it into the constructor.

Thursday, February 7, 2008

Decorator Pattern Afterthoughts

The only issue I ran into with my plan is that if I used the decorator to control whether or not the Viruses can disable antivirus, then I'd be  essentially replecating what I've done with the strategy pattern. For now, I'm just using decorator to make viruses 'stealth', and give them the ability to kill computers. When I think of another use for the strategy pattern, I'll implement it there and then add to my decorator pattern.

Decorator Design Ideas

I'm planning on implementing the Decorator Pattern to give my TrojanVirus and WormVirus classes different capabilities. Basically, I would like to be able to arbitrarily give some viruses (but not all) the ability to do things like be invisible to antivirus, disable antivirus, tunnel through firewalls, take down firewalls, and hose computers (effectively removing them from the simulation).

Observer Pattern: Check!

I finally implemented the observer pattern successfully! It was quite a triumphant moment seeing my classes do stuff without me explicitly telling them to. The observer pattern reminds me of a magic trick. It's clear what's happening behind the curtain, but if I didn't know about the pattern, I might think that somehow my java classes picked themselves up and became slightly sentient.

What I ended up doing was having my Computer class be the observable and then having the instance of antivirus that is created by each computer observe for virus infection. Whenever a Computers boolean isInfected variable is set to true, changed() is called which updates the antivirus instance. When antivirus gets wind of an infection, it checks to make sure that it's enabled and then calls setInfected(false) which sets the isInfected boolean in the computer class to false. This would cause antivirus to get updated again, but since the computer isn't infected, it doesn't do anything.

The second place I implemented the pattern was to have each instance of Computer be an observer and antivirus the observable. This lets the computer's know when their antivirus has been turned on or off. I'm not sure I'll end up using this implementation farther down the line, but it seemed like as good of a place as any to stick the second observer implementation for now as I'm still running with a fairly small amount of classes.

I'd like to mention that I found the extra lecture and lab time devoted to the observer pattern extremely beneficial for my understanding of the pattern. I also met with Daniel earlier in the week to run my ideas past him, which was very positive as well.

Monday, February 4, 2008

Observer Recipe

First you need to figure out which object(s) needs to be the subject and which ones need to be observers.

Then you must decide on whether to use Java's built in observer implementation or if you'd rather create your own infterfaces for Subject and Observer.

If you create your own, you must have methods in the Subject interface for adding and removing observers and for notifying observers that the subject's data has changed. Then in the Observer interface you must have a method for updating the observers with data from the subject.

You now need to implement the Subject and Observer interfaces in the appropriate classes so that you'll have one subject and many observers. The constructor of each observer class should register it with the subject class by calling registerObserver(this).

Now, you can either push out data, sending out whatever the subject has and letting the observers use what they want, or pull specific pieces data into the observers from the subject directly. The pull method requires more getter methods in the class that implements Subject, but seems like the better option in terms of keeping the observers on a need-to-know basis.

In the Subject class, you must create an arraylist to store the observers in and implement the subject interface. If you're going to push data, then you should create a dataChanged() method that will call notifyObservers() whenever the data is changed. notifyObservers() will iterate through the arraylist, pushing each observer the updated data. If you're going to pull data from the subject, let notifyObservers() cause the observer to use the getter methods of the subject class to pull the updated data.

Now, to test your implementation of the Observer Pattern, you need to create an instance of the subject class and observer classes. When you create the observer classes, pass the reference of the subject class to their constructor so that they will be added to the observers arraylist by their constructors.

When you change the data in the subject class, the dataChanged() method will be called, which will in turn call notifyObservers(). From here the new information will either be pushed or pulled to the observers.

If you use Java's built in observer, you don't need to worry about creating the two interfaces. You will need to have the subject class import and extend observable and the observer classes import and implement observer. You'll then need to use setChanged() and notifyObservers() to update the observers. Register observers with addObserver().

Rejoining the land of the living

I took a beating from the flu (or some other nasty bug) during the later half of last week. I've regained most of my ability to use the higher functions of my brain, so I'm now trying to dig myself out from the hole that I'm in.

I've re-read the most juicy bits of the Observer chapter and come up with my recipe for the pattern which will be posted in the next entry. I started using the Java implementation of Observer in the version of my project that I have emailed in, but want to implement my own Observer and Subject interfaces instead. I will continue to hammer away at getting the Observer pattern implemented naturally in two places.

The most obvious place I can think of putting it is to allow antivirus to monitor the computers on the simulated network. The antivirus will be updated whenever a virus tries to infect a computer and if it is enabled, will disinfect the computer before the virus has a chance to mess anything up. Where I'm running into trouble now is where to have the second implementation of the pattern. Once idea that seems decent is to let viruses of the WormVirus class observe the firewalls of computers that they are port-scanning, and be notified of ports when they become open.

Do these two spots sound like good uses of the Observer pattern?

Wednesday, January 30, 2008

Design Patterns Quick-Reference

I saw a relevant post on Reddit.com today which was a Quick-Reference/Cheat-Sheet style PDF for common Design Patterns. There are 23 patterns with UML diagrams and tiny descriptions. I recognize a few of them from class, but most are one's that I haven't heard of (yet).

Here's a link to the original article so I don't forget about it, as it will likely be handy for review purposes.

Friday, January 25, 2008

Strategy Pattern (Lab 2) Redux

Part 1:

Going from a standard OO design using inheritance and abstract classes to one using the Strategy Pattern isn't all that huge of a leap. Instead of having to override behaviors in subclasses that are unable to perform them, you can use a variable to store the type of behavior to perform and then use an interface to perform the behavior.

Joe's problem with SimUDuck stemmed from the fact that he needed to extend it in a way that would add too much complexity to be easily maintained. He was trying to use inheritance to add a fly() method to every sub-Duck by adding it to the main Duck class. This had the unintended effect of granting flight capability to all sub-Ducks, including the ones that aren't supposed to fly: RubberDuck and DecoyDuck. If SimUDuck was a project that would never need maintaining or extending, it wouldn't be too bad to just override fly() in the few subclasses that aren't supposed to fly, but since this project is one that was still in progress, using inheritance and overrides would lead to major headaches for Joe. While this is a valid use of shadowing, it's confusing and doesn't lead to reuse of code.

The Strategy Pattern is a good solution for the problem Joe was faced with because it separates the behaviors from the objects that perform them. The big payoff is that after implementation, the Strategy Pattern provides a more organized and understandable way of reusing and unifying a method across a hierarchy of animates. Joe can add sub-Ducks whenever he wants and make changes to existing behaviors with very little effort compared to if he had just stuck with his standard OO design.

Part 2:


To implement the Strategy Pattern, follow these steps:
1.) Figure out which methods/behaviors are used multiple times across the hierarchy. ex: fly(), quack()
2.) Come up with a naming convention so you can keep all your behaviors straight and create classes for each of the distinct variations of the method, bringing the methods out of the superclass. ex: remove fly() from Duck and create fly(), nofly(), etc in the new classes
3.) Wrap the different versions of the behavior with an interface that can be called when behaviors need to be performed. ex: performFly()
4.) Reference an object of type interface (or rather, whatever you chose to name your interface) and use this object to set up which behavior to use
5.) Change the method in the base class to call the object from above and perform the appropriate method through the interface


Oliver is the 'Observer' cat on the copyright page and was surprisingly difficult to spot since it wasn't on a page that I read the first couple of times. Good trick to get us to re-read the section! :)

Sunday, January 20, 2008

Strategy Pattern (Lab 2)

1.)

Even though the Strategy Pattern adds complexity in terms of the number of classes in your project, the most striking benefit is that it provides a more organized way of modeling the interaction between the subclasses, interfaces, and abstract class by separating the code for executing the behaviors from the animate classes. Another benefit is that you have less duplicated code because the interface for each behavior handles all the work for each of the animates.

Joe's problem was that the relatively simple SimUDuck app needed to be extended in a way that would add a behavior to the subclasses of Duck. Joe's lack of design pattern knowledge led him to leverage inheritance to add a fly() method to Duck. The flaw with this is that every subclass that extends Duck will now be able to fly, even if it's a RubberDuck or DecoyDuck. It wouldn't be too bad to override fly() in the few subclasses that don't fly, but if Joe's manager decided that they wanted to add every variety of duck, living or otherwise, to the simulation, Joe would have to spend many a late night adding overrides to all of the sub-Ducks that can't fly. The Strategy Pattern is great for the SimUDuck project because it's easy to change and when you add methods to one of the behavior interfaces, you don't have to worry about messing up like Joe did and granting a behavior to an animate that shouldn't have it.

2)

-Sort out the methods of the superclass that vary from subclass to subclass. In the SimUDuck example, the stuff that changes is the various implementations of the fly and quack behaviors.

-Create interfaces for your behavior that hide the nitty gritty details of the implementation from the subclasses. The two interfaces in SimUDuck were FlyBehavior and QuackBehavior.

-Add classes for each variation of the stuff that changes that implement the interface, also add instance variables to each subclass that get passed to the interface and tell it which variation to perform. In SimUDuck, each Duck subclass makes calls to the behavior interface and passes it it's own behavior instance variable.

Now, when a Duck calls the performFly() method, the behavior is delegated to the FlyBehavior interface's fly() method which performs the behavior specified by the instance variable.

Thursday, January 10, 2008

Project Proposal

My idea for the term project takes cues from XKCD (a webcomic) and involves simulating the spread of computer viruses through a network of computers. The simulation would be turn based, in the sense that for every period of time, each animate object would be alloted one action.


Each simulated computer would be assigned a unique IP address and would be able to exchange email, execute email attachments, and visit a selection of simulated websites and download files from them. Individual computers would also need to have their own email addresses and address books, containing the addresses of a random selection of other computers' on the network.


Some machines would act as clients, with only one connection to the rest of the network, and others would be servers, which would have many connections. The computers would have antivirus and firewalls (though not all of them would have these security features enabled) and they would also either be up to date with the latest security patches and virus updates or not be up to date.


I envision three to four types of viruses existing in this simulation, but there is room for more if I can think of how to implement them. E-Mail Trojans would e-mail themselves around the network to single or multiple recipients who would be infected if they executed the attachments, Worms would scan network for open ports on computers that do not have the latest security updates. Some of the viruses would be able to defeat antivirus software and disable firewalls, and others would simply take down machines. Resident Viruses would embed themselves in files that would be downloaded from the 'internet' by the computers and would infect them upon being executed. Malicious code could also exist on websites, mimicking some of the nasty Active-X scripts that exist on the real internet.


For the simulated web-browsing to work, there would need to be a list of available websites, some of which would contain malicious code, and others would be clean. If a computer is browsing the web, it has a chance of downloading a file from the website, which may or may not be infected.


Antivirus software would be able to scan the computers for viruses and then attempt to remove any that they find. The viruses would all have a creation date, and each instance of the antivirus software would contain a variable storing the date of the most recent virus definition update. These two dates would be compared in order to decide whether or not the antivirus software would be able to remove the viruses.


The animate objects would obviously be the active viruses, since they would be move about. The resident viruses and malicious web code would be inactive because the computer would have to perform an action on them in order to be infected. The computers could also be considered active, since they will send emails and browse the web without necessarily being infected. Antivirus software would be able to scan for viruses and then remove them if any were found, this makes them reactive inanimates, since the antivirus software won't be moving around.


The hierarchies in this projects would consist of:

Animates:

- Computers

- Worms

- Email Trojans


Inanimates:

- Firewalls

- Antivirus

- Resident Viruses

- Malicious Web Code


Locations:

- Each simulated machine would be it's own location


Actions:

Computers - visit website, download file, send email, read email, execute email attachment

General Virus Actions - infect, disable antivirus, disable firewall, disable automatic updates

Worms - scan ports, exploit security hole

Email Trojans - get contents of email address book, propagate through email, format c:/

Antivirus - Update definitions, scan computer, remove/quarantine virus

Resident Viruses and Malicious web code - infect computer when file is opened or website is visited

Monday, January 7, 2008

First Post! (Eclipse)

My first reaction to Eclipse was that it looked complicated and cluttered. I quickly discovered during the lab that it actually isn't all that complicated, just slightly different from the text-editor/terminal workflow I got used to last term.

Creating a project was straightforward and I can tell that being able to browse projects via the Package Explorer will become more valuable as the amount of classes in the project increases (it seemed to be overkill for my 2 class test project, though).

I'll likely get along just fine with this IDE as I was somewhat annoyed by the number of windows I had to have open last term while coding. Instead of switching between a text editor, terminal, and Firefox, I can do everything in Eclipse and it will even auto-complete my code for me. yay!

The export to archive process went smoothly and produced a nice little .zip containing the whole project.