Design Pattern - Basic
Design Pattern - Basic
Deeper:
y Design Patterns:
http://c2.com/cgi/wiki?DesignPatterns
y C# examples
http://www.dofactory.com/Patterns/Patterns.aspx
y Java examples
http://www.patterndepot.com/put/8/JavaPatterns.htm
CSE 403, Spring 2007, Alverson
Popular patterns we’ll explore
y Creational
o Singleton
o Factory
y Structural
o Decorator
o Flyweight
y Behavioral
o Iterator
o Strategy
y Why we care:
o Creating lots of objects can take a lot of time
o Extra objects take up memory
o It is a maintenance headache to deal with different
objects floating around if they are the same
private RandomGenerator() {}
...
}
y possible problem with this class?
Always creates the instance, even if the class
is not used.
CSE 403, Spring 2007, Alverson
Singleton example 2
y variation: don't create the instance until needed
// Generates random numbers
public class RandomGenerator {
private static RandomGenerator gen = null;
public static RandomGenerator getInstance() {
if (gen == null) {
gen = new RandomGenerator();
}
return gen;
}
...
}
private Flyweighted() {}
y benefits:
o supports variations in the traversal of an aggregate
o simplifies the aggregate’s interface
o allows more than one traversal to be pending on an
aggregate
o removes need to know about internal structure of
collection or different methods to access data from
different collections – puts knowledge in the iterator
y examples:
o file saving/compression
o layout managers on GUI containers
o AI algorithms for computer game players
// setting a strategy
player1.setStrategy(new SmartStrategy());
// using a strategy
Card p1move = player1.move(); // uses strategy