个人理解是Strategy模式包含:Strategy 接口,implements于该接口的Strategy1、Strategy2、......., 一个Strategy选择器
以下是一个简单例子
策略部分
package demo;
/*
* 策略接口
*/
public interface Human {
void printType();
}
package demo;
/**
* 策略1
* @author yz
*
*/
public class She implements Human{
@Override
public void printType() {
System.out.println("She");
}
}
package demo;
/**
* 策略2
* @author yz
*
*/
public class Person implements Human {
private String name;
{
name="init";
}
public Person() {
}
public Person(String s) {
this.name=s;
}
public String getName() {
return name;
}
@Override
public void printType() {
System.out.println("Person");
}
}
package demo;
/**
* 策略3
* @author yz
*
*/
public class He implements Human{
@Override
public void printType() {
System.out.println("He");
}
}
选择器部分
package demo;
/**
* 策略选择器
* @author yz
*
*/
public class HumanContext {
private Human strategy=null;
public HumanContext(Human human) {
this.strategy=human;
}
public Human getStrategy() {
return strategy;
}
public void setStrategy(Human strategy) {
this.strategy = strategy;
}
}
调用策略
package demo;
public class Main {
public static void main(String[] args) {
HumanContext h= new HumanContext(new Person());
h.getStrategy().printType();
h.setStrategy(new She());
h.getStrategy().printType();
h.setStrategy(new He());
h.getStrategy().printType();
}
}
运行结果:
Person
She
He