策略模式,它主要的作用是封装算法,是一种行为模式。
2、具体算法策略:
3、策略引用:
有三种角色:
1、具体算法角色:具体的算法的实现;
2、抽象策略角色:抽象类或接口,提供具体算法角色的抽象;
3、上下文角色:实现对具体算法角色的引用。
更详细定义参照:策略模式。
代码时间:
1、具体实现:
package com.array7.strategy;
public class Run
{
public static void main(String[] args)
{
new Context(new Strategy1()).execute();
new Context(new Strategy2()).execute();
new Context(new Strategy3()).execute();
}
}
2、具体算法策略:
package com.array7.strategy;
public class Strategy1 implements IStrategy {
@Override
public void execute() {
System.out.println("stargtegy1.execute...");
}
}
package com.array7.strategy;
public class Strategy2 implements IStrategy {
@Override
public void execute() {
System.out.println("stargtegy2.execute...");
}
}
package com.array7.strategy;
public class Strategy3 implements IStrategy {
@Override
public void execute() {
System.out.println("stargtegy3.execute...");
}
}
3、抽象接口:
package com.array7.strategy;
public interface IStrategy {
void execute();
}
3、策略引用:
package com.array7.strategy;
public class Context {
private IStrategy strategy;
public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void execute() {
this.strategy.execute();
}
}