策略模式指一个类的行为可以在运行时更改,这种类型的设计模式属于行为型模式。
一、需求举例:
项目中需求开发应用场景:
1.简单的项目开发由初级工程师完成;
2.中等难的项目开发由中级工程师完成;
3.高难度的项目开发由高级工程师完成;
4.难度过高的项目默认拒绝。
二、类图
三、代码实战
1.接口:Engineer.java
package com.lance.strategy;
public interface Engineer {
default void develop(String program) {
System.out.println("Engineer default refuse " + program);
}
}
2.初级工程师类:JuniorEngineer.java
package com.lance.strategy;
import com.lance.strategy.Engineer;
public class JuniorEngineer implements Engineer {
@Override
public void develop(String program) {
System.out.println("Junior Engineer finish " + program);
}
}
3.中级工程师类:IntermediateEngineer.java
package com.lance.strategy;
import com.lance.strategy.Engineer;
public class IntermediateEngineer implements Engineer {
@Override
public void develop(String program) {
System.out.println("Intermediate Engineer finish " + program);
}
}
4.高级工程师类:SeniorEngineer.java
package com.lance.strategy;
import com.lance.strategy.Engineer;
public class SeniorEngineer implements Engineer {
@Override
public void develop(String program) {
System.out.println("Senior Engineer finish " + program);
}
}
5.工程师上下文类:EngineerContext.java
package com.lance.strategy;
public class EngineerContext {
private Engineer engineer;
public EngineerContext(Engineer engineer) {
this.engineer = engineer;
}
public void develop(String program) {
engineer.develop(program);
}
}
6.主类:StrategyPattern.java
package com.lance.strategy;
public class StrategyPattern {
public static void main(String[] args) {
System.out.println("==========start==========");
EngineerContext context = new EngineerContext(new JuniorEngineer());
context.develop("easy program");
System.out.println("=======================");
context = new EngineerContext(new IntermediateEngineer());
context.develop("middle program");
System.out.println("=======================");
context = new EngineerContext(new SeniorEngineer());
context.develop("difficult program");
System.out.println("=======================");
context = new EngineerContext(new Engineer() {
});
context.develop("too difficult program");
System.out.println("==========end==========");
}
}
输出结果:
==========start==========
Junior Engineer finish easy program
=======================
Intermediate Engineer finish middle program
=======================
Senior Engineer finish difficult program
=======================
Engineer default refuse too difficult program
==========end==========
网友评论