package com.atguigu.java;
//接口的应用:工厂方法的设计模式 //体会:面向接口编程的思想 public class FactoryMethodTest { public static void main(String[] args) { IWorkFactory factory = new StudentWorkFactory(); Work work = factory.getWork(); work.doWork(); IWorkFactory factory1 = new TeacherWorkFactory(); Work work1 = factory1.getWork(); work1.doWork(); } } interface IWorkFactory{//在接口中不指名到底造什么对象,在具体的实现类中才指明到底要造什么对象。 //若接口改为类就是很正常的返回对象的操作,这里接口我可以写成抽象类,抽象类里有抽象方法,返回值为Work Work getWork(); }class StudentWorkFactory implements IWorkFactory{
public Work getWork() { return new StudentWork(); } }
class TeacherWorkFactory implements IWorkFactory{
public Work getWork() { return new TeacherWork(); } }interface Work{
void doWork(); }class StudentWork implements Work{
public void doWork() { System.out.println("学生学习,写作业!"); } }
class TeacherWork implements Work{
public void doWork() { System.out.println("老师讲课,批作业!"); } }