搜尋此網誌

2012年12月30日 星期日

Command design pattern (命令設計模式)

package Patern;

public class CommandPattern {
 
 public static void main(String [] args){
  
  int a = 10;
  
  if(0 <= a && a < 3){
   System.out.println(a + "is  0 - 2");
  }else if(3 <= a && a < 7){
   System.out.println(a + "is  3 - 6");
  }else{
   System.out.println(a +" is larger than 6");
  }
  
  /**
   * Following is a example of using command pattern to extract if-else expressions
   * into the class.
   */

  
  ICompare[] compareEvents = new ICompare[]{new LessEvent(), new BetweenEvent() ,new LargeEvent()}; 
  for(int i = 0 ; i < compareEvents.length ; i++){
   compareEvents[i].print(a);
  }
 }

}

interface ICompare{
 public void print(int number);
}

class LessEvent implements ICompare{

 @Override
 public void print(int a) {
  if(0 <= a && a < 3){
   System.out.println(a + "is  0 - 2");
  }
 }
}

class BetweenEvent implements ICompare{

 @Override
 public void print(int a) {
  if(3 <= a && a < 7){
   System.out.println(a + "is  3 - 6");
  }
  
 }
}

class LargeEvent implements ICompare{

 @Override
 public void print(int number) {
  if(number  > 6){
   System.out.println(number +" is larger than 6");
  }
 }
}