工厂模式主要解决接口选择的问题,相对比较简单,而且常用。
一、需求举例:
项目中需求开发应用场景:
1.如果初级工程师能够完成,就让初级工程师完成,否则交给中级工程师;
2.如果中级工程师能够完成,就让中级工程师完成,否则交给高级工程师;
3.如果高级工程师能够完成,就让高级工程师完成,否则交给Top工程师拒绝需求;
二、代码实例
父类接口:Engineer.java
package com.lance.factory;
public interface Engineer {
int EASY = 1;
int MIDDLE = 2;
int DIFFICULT = 3;
default void develop(String program) {
System.out.println("Engineer default refuse " + program);
}
}
初级工程师类:JuniorEngineer.java
package com.lance.factory;
public class JuniorEngineer implements Engineer{
@Override
public void develop(String program) {
System.out.println("Junior Engineer finish " + program);
}
}
中级工程师类: IntermediateEngineer.java
package com.lance.factory;
public class IntermediateEngineer implements Engineer {
@Override
public void develop(String program) {
System.out.println("Intermediate Engineer finish " + program);
}
}
高级工程师类:SeniorEngineer.java
package com.lance.factory;
public class SeniorEngineer implements Engineer{
@Override
public void develop(String program) {
System.out.println("Senior Engineer finish " + program);
}
}
工程师工厂类:EngineerFactory.java
package com.lance.factory;
public class EngineerFactory {
static Engineer getEngineer(int difficulty) {
Engineer engineer = null;
switch (difficulty) {
case Engineer.EASY:
engineer = new JuniorEngineer();
break;
case Engineer.MIDDLE:
engineer = new IntermediateEngineer();
break;
case Engineer.DIFFICULT:
engineer = new SeniorEngineer();
break;
default:
engineer = new Engineer() {
};
break;
}
return engineer;
}
}
工厂模式主类: FactoryPattern.java
package com.lance.factory;
public class FactoryPattern {
public static void main(String[] args) {
System.out.println("==========start==========");
Engineer engineer = EngineerFactory.getEngineer(Engineer.EASY);
engineer.develop("easy program");
System.out.println("=======================");
engineer = EngineerFactory.getEngineer(Engineer.MIDDLE);
engineer.develop("middle program");
System.out.println("=======================");
engineer = EngineerFactory.getEngineer(Engineer.DIFFICULT);
engineer.develop("difficult program");
System.out.println("=======================");
engineer = EngineerFactory.getEngineer(100);
engineer.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==========
网友评论