1-策略模式

Creating a method that behaves differently depending on the argument object that you pass it is called the Strategy design pattern.

1

策略模式很简单,又无处不在,要逐步从简单讲到复杂。此时在一个方法中,想要根据不同的输入有不同的输出时该怎么办呢?如下

int calculate (int i){
  return i + 1;
}

2

上面的代码很简单对吧,根据不同的输入有不同的输出,但是如果我的输入不是原始类型该怎么办呢,如下

public class Student {
    private int age;
    public Student(int age) {
        this.age = age;
    }
    public getAge(){
      return age;
    }
}
int getAgeOfSomeone(Student s){
    return s.getAge();
}

3

上面的代码也很简单,根据不同的实例输出特定的age。但是如果我不仅仅想输出studnet.age,我也想输出teacher.age该怎么办呢,这是两个不同的类,这时就需要重载了。

public class Student {
    private int age;
    public Student(int age) {
        this.age = age;
    }
    public getAge(){
      return age;
    }
}
public class Teacher {
    private int age;
    public Teacher(int age) {
        this.age = age;
    }
    public getAge(){
      return age;
    }
}
int getAgeOfSomeone(Student s){
    return s.getAge();
}

int getAgeOfSomeone(Teacher t){
    return t.getAge();
}

一种更聪明的做法是指定一个student和teacher共同的行为,作为标记放到arguemnt list中。这样在业务复杂时,就要更好用一些。

interface HaveAge {
    int getAge();
}
class Student implements HaveAge {
    private int age;

    public Student(int age) {
        this.age = age;
    }

    @Override
    public int getAge() {
        return age;
    }
}
class Teacher implements HaveAge {
    private int age;

    public Teacher(int age) {
        this.age = age;
    }

    @Override
    public int getAge() {
        return 0;
    }
}
int getAgeOfSomeone(HaveAge person){
    return person.getAge();
}

4

其实上面3种都是策略模式的实现,只是抽象程度从低到高,更高一层还有泛型(generics)没有讲,但是理解策略模式已经足够了。

上一篇:Java8中实现对象之间比较


下一篇:Lambda表达式的应用