- Published on
CS 3500 Day 6
- Authors
- Name
- Jacob Aronoff
Object Oriented Design
Today we're talking about the static keyword. Static properties are owned by a class not an object. A cooler way to use static, however, is with inner static classes.
class Widget {
private Widget(...) { ... }
public static class Factory {
public Factory() { ... }
public Widget create(...) {
...
++widgetIdCounter;
...
}
private int widgetIdCounter;
}
}
Basically, the reason we do this is because we only want to make a factory in the context of widgets. We can then access it like so:
Widget.Factory factObj = Widget.factory();
Widget w1 = factObj.create();
Widget w2 = factObj.create();
When to use statics:
- fields: one variable for the whole class rather than one per object
- methods: a method associated with the class that doesn't dependf on an instance
- class: associated classes
Now we're talking about generics in java, and their dangers.
class BinTree<T> { ... } // generic class
<T> void permute(List<T>); // generic method
When it's a type, use a parameter:
BinTree<Widget> tree = new BinTree<Widget>();
When it's a constructor, <>
asks Java to guess:
BinTree<Widget> tree = new BinTree<>();
When using a static member, don't use a parameter:
if (h < BinTree.MAX_HEIGHT) {
return BinTree.singleton(value);
}
Using generics is dangerous because of backwards compatability. In older versions of java, generics type checking was bad. Instead use wildcard types.
List<?>
Finally, we're getting to design. We start with the class OOD structure: MVC (Model-View-Controller). The point of this pattern is to seperate as much as possible; no tight coupling. We want to be able to replace a part with another very easily. The controller doesn't care how the model does its job, it just relys on the fact that it will get it done. The view just show things.
Model:
- Enforces information integrity
- For games, it means enforcing the rules
- All actions are here
tic tac toe example
OO analysis:
Our TTT model needs to:
- Play a move as X
- Play a move as O
- Find out whose turn it is
- Find out the contents of the grid
- Find out if the game is over
- Find out who the winner is (if any)
Error conditions:
- Play out of turn
- Play in an occupied cell
- Plau after the gamer has ended
Now we're talking about a generic connect N game:
We need:
- move a disk
- game over
- whose turn is it?
- start a new game
- get the board
The best way to do MVC is by designing an interface by brainstorming the methods, coming up with the signature, and then reimplementing. Now onto a new pattern:
Builder
Next class we're going to be talking more about the builder pattern.