您的位置:首页 > 编程语言

2010/7/30 初学设计模式、责任链实现filter、面向接口编程、策略模式修改排序算法

2010-07-30 22:29 701 查看
       在前天的排序算法中不知道使用Comparable接口继承来复用代码,通过今天的设计模式学习可以使用策略模式,例如让不同的类继承Comparable接口,对其比较方式实现Comparator接口写出不同的比较策略,之后只要在compareTo方法中使用不同的比较策略就可以实现而不用修改很多代码。

package com.gavin.test;

import java.util.Comparator;

public class Cat implements Comparable<Cat> {

private int height;

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

@Override
public int compareTo(Cat o) {
return new HeightComparator().compare(this, o);
}

public Cat(int height) {
super();
this.height = height;
}

@Override
public String toString(){
return height + "";
}
private class HeightComparator implements Comparator<Cat>{

@Override
public int compare(Cat o1, Cat o2) {
if(o1.height > o2.height){
return 1;
} else if(o1.height == o2.height) {
return 0;
}
return -1;
}

}

}


      通过面向接口编程可以较为方便开发,代码复用性也比较好。里面的实现方式必存在多态。其中在使用多态是使用类继承还是用接口可以用这种方式理解:有一定概念的例如交通工具可以作为类的继承,而一类事物的共同特点的可以用接口,xxxable例如Comparable。

      在上一次的农场的作业中发现在遍历容器类时添加元素会出现ConcurrentModificationException,以下是转载内容:

Iterator的一个基本概念没有掌握导致的这个错误,就是在Iterator的实现类
比如Hashtable里面的内部类
 private class Enumerator<T> implements Enumeration<T>, Iterator<T>

            

    

会在next,或者remove的时候检查当前集合是否会在修改状态,如果是的话
就会抛出 ConcurrentModificationException,而他自己remove则是使用了同步的方法
而且同步了modCount;expectedModCount;代码:

public T next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
return nextElement();
}

public void remove() {
if (!iterator)
throw new UnsupportedOperationException();
if (lastReturned == null)
throw new IllegalStateException("Hashtable Enumerator");
if (modCount != expectedModCount)
throw new ConcurrentModificationException();

synchronized(Hashtable.this) {
Entry[] tab = Hashtable.this.table;
int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;

for (Entry<K,V> e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e == lastReturned) {
modCount++;
expectedModCount++;
if (prev == null)
tab[index] = e.next;
else
prev.next = e.next;
count--;
lastReturned = null;
return;
}
}
throw new ConcurrentModificationException();
}
}
}


而自己在next的同时,修改了这个集合,导致了这个错误的出现。

  

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息