Magazine
 
Design Pattern
 

return input.getText();
}
private class InformDisplay extends Observable {
public void notifyObservers() {
setChanged();
super.notifyObservers();
}
public String getChange() {
return input.getText();
}
}
//...
}

As we pass the command "java Show" on the command prompt, two windows are displayed. In which the first window takes the input from the user and the other window displays the inputted data.

II.State Design Pattern

The State pattern is used whenever an enclosing class switches among the number of related contained classes and passes the method calls on the current contained class. This design pattern switches between internal
classes in such a manner that the enclosing object appears to change its state. This design pattern also provides memory for the instance variables of a class. It localizes the state-specific behavior and partitions behavior for different states. It makes the explicit transition.

Here is an example that demonstrate State
Design Pattern.

StateContext.java

public class StateContext {
private StateName StateName;
public StateContext() {
setStateName(new StateNameStars());
//start with stars
}
public void setStateName(StateName StateNameIn) {
this.StateName = StateNameIn;
}

 

public void showName(String nameIn) {
this.StateName.showName(this, nameIn);
}
}

StateName.java

public interface StateName {
public void showName(StateContext StateContext,
String nameIn);
}

StateNameExclaim.java

public class StateNameExclaim
implements StateName {
public StateNameExclaim() {}
public void showName(StateContext StateContext,
String nameIn) {
System.out.println(nameIn.replace(' ','!'));
//
show exclaim only once, switch back to stars
StateContext.setStateName(new StateNameStars());
}
}

StateNameStars.java

public class StateNameStars implements
StateName {
int starCount;
public StateNameStars() {
starCount = 0;
}
public void showName(StateContext StateContext,
String nameIn) {
System.out.println(nameIn.replace(' ','*'));
//
show stars twice, switch to exclamation point
if (++starCount > 1) {
StateContext.setStateName(
new StateNameExclaim());
}
}
}

Feb 2008 | Java Jazz Up |60
previous
index
next
 
 
View All Topics
All Pages of this Issue
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 ,

Download PDF