removeIf comparator fileFilter
理解策略设计模式
出行时,可以选择多种出行方式,比如火车,飞机,汽车,不管哪种出行方式,目的地是一样的
实现策略模式
- 环境类(context):用来操作策略的上下文环境(游客)
- 抽象策略类(strategy):策略的抽象,出行方式的抽象
- 具体策略类(concreteStrategy):具体的策略实现,每一种出行方式的具体实现
抽象策略接口(strategy)
public interface TravelStrategy {
public void travelStyle();
}
具体策略类(concreteStrategy)
class Train implements TravelStrategy{
@Override
public void travelStyle() {
System.out.println("火车");
}
}
class High implements TravelStrategy{
@Override
public void travelStyle() {
System.out.println("高铁");
}
}
class Plane implements TravelStrategy{
@Override
public void travelStyle() {
System.out.println("飞机");
}
}
环境类(context)
public class Traveler {
TravelStrategy travelStrategy;
public void setTravelStrategy(TravelStrategy ts){
this.travelStrategy=ts;
}
public void travelStyle(){
travelStrategy.travelStyle();
}
public static void main(String[] args) {
Traveler t=new Traveler();
t.setTravelStrategy(new Train());
t.travelStyle();
}
}
优点
策略模式遵循开闭原则,实现代码的解耦
灵活
与其他模式的区别
- 与状态模式的区别
策略模式致使条件选择的方法,只执行一次方法,而状态模式是随着状态的改变不停地更改执行方法
- 与工厂模式的区别
工厂模式是创建模式,他关注对象的创建,提供对象创建的接口,让对象的创建和具体使用的客户无关,策略模式是对象行为型模式,他关注行为和算法的封装
举例
ArrayList的removeIf就是策略设计模式,参数是Predicate,是个接口,根据不同的需求,来写不同的策略
- Predicate是抽象策略(strategy)
- 实现类是具体策略(concreteStrategy)
- list的removeIf方法是环境类(context)
//策略设计模式,匿名内部类
/**
* 基于指定的条件删除集合中的数据
* 多态,Perdicate接口作为函数的参数
* 策略 每一个Predicate接口的子实现都是一种实现
* 回调函数
* @param allPerson
*/
public class TestRemoveIf {
public static void deletePersonByIf1(ArrayList<String> list) {
boolean flag = list.removeIf(new Predicate<String>() {
// 回调函数
@Override
public boolean test(String t) {
boolean flag = false;
if (((String) t).startsWith("李")) {
flag = true;
}
return flag;
}
});
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("张三");
list.add("王五");
list.add("张潇");
list.add("李四");
TestRemoveIf.deletePersonByIf1(list);
for (String s : list) {
System.out.println(s);
}
}
}
打开源码看removeIf,里面用到了predicate的test重写后的方法
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
removeIf的参数是接口类型
removeIf在调用时,用匿名内部类的方式,重写实现接口Predicate里的test方法
test是boolean类型,判断条件满足时返回true,满足条件的即被删除