对可能需要修改的方法开放

来源:互联网 发布:世界人工智能专业排名 编辑:程序博客网 时间:2024/05/22 03:59

 // 按照色温排序
 public void sort_1() {
  for (int i = 0; i < mCurrent; i++) {
   for (int j = 0; j < mCurrent - i - 1; j++) {
    if (this.lights[j].getCt() < this.lights[j + 1].getCt()) {
     Light temp = this.lights[j];
     this.lights[j] = this.lights[j + 1];
     this.lights[j + 1] = temp;
    }
   }
  }
 }

如上程序,当需要按照Ct排序时则需要增加方法。但是这样做比较麻烦,有一种更为简便的方法

 public void sort(Compareable compareable) {
   for (int i = 0; i < mCurrent; i++) {
    for (int j = 0; j < mCurrent - i - 1; j++) {
     if (compareable.compare(lights[j], lights[j+1])<0) {
      Light temp = this.lights[j];
      this.lights[j] = this.lights[j + 1];
      this.lights[j + 1] = temp;
     }
    }
   }
  }

将可能修改的方法抽象成一个借口

public interface Compareable {
 public int compare(Light l1, Light l2);
}

当需要改变时

public class CtCompareable implements Compareable{

 @Override
 public int compare(Light l1, Light l2) {
  
  return l1.getCt() - l2.getCt();
 } 
}

需要使用时

Compareable c  = new CtCompareable();

XXX.sort(c);

多态性,根据c的不同选择不同的类。