工厂模式

还没有将工厂模式应用到实际的项目中去,今天学习了下,将其记录如下:

public class FactoryTest {
public static void main(String[] args) {
IWorkFactory i=new StudentWorkFactory();//接口的实现类由下面的接口的具体实现类实现
i.getWork().work();//教师的工作 去工作的接口中用具体方法去实现

IWorkFactory i1=new TeacherWorkFactory();
i1.getWork().work();
}}

interface IWorkFactory{
Work getWork();
}
class StudentWorkFactory implements IWorkFactory{

@Override
public Work getWork() {
return new StudentWork();
}
}
class TeacherWorkFactory implements IWorkFactory{
@Override
public Work getWork() {
return new TeacherWork();
}
}
interface Work{
void work();//接口中的方法默认为public abstract
//接口中的变量默认为public static final

}
class StudentWork implements Work{
public void work(){
System.out.println("学生在读书");
}
}
class TeacherWork implements Work{
public void work(){
System.out.println("老师批改作业");
}
}
posted @ 2017-10-28 18:58  kelly_one  阅读(244)  评论(0编辑  收藏  举报