策略模式

策略模式,顾名思义,就是将做某件事的各种方式,封装成一个个策略,根据具体需求调用:java里面典型的例子有Comparator 。

假设现在有一些猫,我们要比较它们的大小。现在有两种比较策略,根据高度比较和根据体重比较;

首先,我们的猫:

package com.lin.strategy;

/**
 * 猫类
 * @author lin
 *
 */
public class Cat {
    
    /**
     * 高度
     */
    private int height;
    
    /**
     * 体重
     */
    private int weight;
    
    public Cat() { }
    
    public Cat(int height, int weight) {
        this.height = height;
        this.weight = weight;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
    }
    
    @Override
    public String toString() {
        return "{height:"+height+";weight:"+weight+"}";
    }
    
}

 

现在,我们有很多只猫,我们需要根据策略为它们排序:

1.编写一个自定义的Comparator,根据高度比较

package com.lin.strategy;

import java.util.Comparator;

public class HeightComparator implements Comparator{

    @Override
    public int compare(Object obj, Object other) {
        if(obj instanceof Cat && other instanceof Cat) {
            Cat c1 = (Cat)obj;
            Cat c2 = (Cat)other;
            if(c1.getHeight() > c2.getHeight()) {
                return 1;
            }else if(c1.getHeight() < c2.getHeight()) {
                return -1;
            }else {
                return 0;
            }
        }
        throw new RuntimeException("类型不同,无法比较!");
    }

}

2.第二个自定义的Comparator,根据体重比较

package com.lin.strategy;

import java.util.Comparator;

public class WeightComparator implements Comparator{

    @Override
    public int compare(Object obj, Object other) {
        
        if(obj instanceof Cat && other instanceof Cat) {
            Cat c1 = (Cat)obj;
            Cat c2 = (Cat)other;
            if(c1.getWeight() > c2.getWeight()) {
                return -1;
            }else if(c1.getWeight() < c2.getWeight()) {
                return 1;
            }else {
                return 0;
            }
        }
        throw new RuntimeException("类型不同,无法比较!");
    }

}

现在我们就可以根据不同策略进行比较大小了:

package com.lin.strategy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        
        List<Cat> cats = new ArrayList<Cat>();
        cats.add(new Cat(5,5));
        cats.add(new Cat(3,3));
        cats.add(new Cat(1,1));
        
        //根据高度比较
        Collections.sort(cats,new HeightComparator());
        for(Cat cat : cats) {
            System.out.println(cat);
        }
        
        //根据体重比较
        Collections.sort(cats,new WeightComparator());
        for(Cat cat : cats) {
            System.out.println(cat);
        }
    }
}

 

posted on 2017-04-08 19:47  一只野生程序猿  阅读(87)  评论(0)    收藏  举报

导航