1 public class TestFactoryMethod { 2 public static void main(String[] args) { 3 IWorkFactory i = new StudentWorkFactory(); 4 i.getWork().doWork(); 5 6 IWorkFactory i1 = new TeacherWorkFactory(); 7 i1.getWork().doWork(); 8 } 9 } 10 11 interface IWorkFactory{ 12 Work getWork(); 13 } 14 class StudentWorkFactory implements IWorkFactory{ 15 16 @Override 17 public Work getWork() { 18 return new StudentWork(); 19 } 20 21 } 22 class TeacherWorkFactory implements IWorkFactory{ 23 24 @Override 25 public Work getWork() { 26 return new TeacherWork(); 27 } 28 29 } 30 31 interface Work{ 32 void doWork(); 33 } 34 35 class StudentWork implements Work{ 36 37 @Override 38 public void doWork() { 39 System.out.println("学生写作业"); 40 } 41 42 } 43 class TeacherWork implements Work{ 44 45 @Override 46 public void doWork() { 47 System.out.println("老师批改作业"); 48 } 49 50 }
时间: 2024-11-25 18:16:24