Lec_7 Java Design Patterns Part 1 (1)
Lec_7 Java Design Patterns Part 1 (1)
The solution describes the elements that make up the design, their
relationships, responsibilities, and collaborations.
▪ Here, x is a base class and classes xy and xz are derived from it.
▪ The Factory is a class that decides which of these subclasses to
return depending on the arguments you give it.
▪ The getClass() method passes in some value abc, and returns
some instance of the class x. Which one it returns doesn't matter
to the programmer since they all have the same methods, but
different implementations.
Java Design Patterns 13
The Factory Pattern
:: The Base Class
▪ Let's consider a simple case where we could use a Factory class. Suppose we
have an entry form and we want to allow the user to enter his name either as
“firstname lastname” or as “lastname, firstname”.
▪ Let’s make the assumption that we will always be able to decide the name
order by whether there is a comma between the last and first name.
class Namer { //a class to take a string apart into two names
protected String last; //store last name here
protected String first; //store first name here
public String getFirst() {
return first; //return first name
}
public String getLast() {
return last; //return last name
}
}
Java Design Patterns 14
The Factory Pattern
:: The First Derived Class
In the FirstFirst class, we assume that everything before the last
space is part of the first name.
class FirstFirst extends Namer {
public FirstFirst(String s) {
int i = s.lastIndexOf(" "); //find separating space
if (i > 0) {
first = s.substring(0, i).trim(); //left = first name
last =s.substring(i+1).trim(); //right = last name
} else {
first = “” // put all in last name
last = s; // if no space
}
}
}