Press "Enter" to skip to content

Java设计模式—策略模式(strategy pattern)

所谓策略模式,即创建一个根据所传递参数对象的不同具有不同行为的方法,这主要是依据多态实现的。

将基类作为参数定义某方法,而实际传入不同的子类对象,也就通过后期绑定调用了不同的方法,即采取了不同的策略。

abstract class PersonComing {
    abstract void process(Person person);
}
class FriendComing extends PersonComing {
    void process(Person friend) {
        System.out.println("say hello to " + friend);
    }
}
class ThiefComing extends PersonComing {
    void process(Person thief) {
        System.out.println("call 110 to arrrest " + thief);
    }
}
class Person {
    String name;
    Person(String str) {
        name = str;
    }
    public String toString() {
        return name;
    }
}
public class Test {
    static void deal(PersonComing meet, Person person) {
        meet.process(person);
    }
    public static void main(String[] args) {
        Person friend = new Person("Tom");
        Person thief = new Person("Tim");
        deal(new FriendComing(),friend); //output: say hello to Tom
        deal(new ThiefComing(),thief); //output: call 110 to arrest Tim
    }
}

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax