原创 策略设计模式实例(欢迎指正交流)

在网页http://topic.csdn.net/u/20090916/00/8204215a-73c8-4939-9ccf-258ded13e33f.html上看到一道面试题,如下:

利用Java中的接口来实现设计模式中的策略模式,需要编写程序如下: 

  public interface Relation{ 

    boolean Releation(int a,int b);   } 

 利用上述接口,编写一个函数 

   IntGetMaxChainLen(int[] intArray,Relation relation); 

  intArray为一个整形数组,该数组中,假如相令俩整数a,b。使得Relation(a,b)为true,则认为a,b形成一段链;计算该数组中(根据Relation关系)最长的链的长度; 

 假如没有这样的链返回为0; 

 要求:根据上述条件,代码中要实现GetMaxChainLen函数,还要给出一中Releation的实现。给出完整可运行的测试代码。 

 

自己动手编写的程序如下:

package stratagy.chainLength;

public interface Relation {

 public boolean relation(int a,int b);
}

 

 

package stratagy.chainLength;

public class RelationEqual implements Relation {

 public boolean relation(int a, int b) {
  // TODO Auto-generated method stub
  return (a==b);
 }

}

 

 

package stratagy.chainLength;

public class RelationGreater implements Relation {

 public boolean relation(int a, int b) {
  // TODO Auto-generated method stub
  return a>b;
 }

}

 

 

package stratagy.chainLength;

public class RelationLess implements Relation {

 public boolean relation(int a, int b) {
  // TODO Auto-generated method stub
  return (a<b);
 }

}

 

 

package stratagy.chainLength;

public class Chain {
 private Relation relation;
 private int[]chain ;
 
 public void setRelation(Relation relation) {
  this.relation = relation;
 }

 public Chain(Relation relation, int[] chain) {
  super();
  this.relation = relation;
  this.chain = chain;
 }

 int getMaxChainLen(int[] chain,Relation relation){
  int maxLength = 0;
  int a;
  int b;
  for(int i = 0;i < chain.length - 1;i++){
   a = chain[i];
   b = chain[i + 1];
   if(relation.relation(a, b)){
    maxLength++;
   }
  }
  return maxLength;
  
 }

}

 


public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Relation relation = new RelationGreater();
  int [] intArray = {2,5,-4,8,8,90,-12,0,0,0,-4,5,67,23,21};
  Chain chain = new Chain(relation,intArray);
  System.out.println(chain.getMaxChainLen(intArray, relation));
  
  relation = new RelationEqual();
  chain.setRelation(relation);
  System.out.println(chain.getMaxChainLen(intArray, relation));
  
  relation = new RelationLess();
  System.out.println(chain.getMaxChainLen(intArray, relation));
 }

}

 

 

输出结果如下:

5

3

6

 

 

posted @ 2011-12-01 11:38  Flying Dreams  阅读(168)  评论(0编辑  收藏  举报