工厂设计模式

 IWorkFactory.java

 

  
  
  
  
  1. public interface IWorkFactory { 
  2.     Work getWork(); 

 

StudentWorkFactory.java

 

  
  
  
  
  1. public class StudentWorkFactory implements IWorkFactory { 
  2.  
  3.     @Override 
  4.     public Work getWork() { 
  5.         // TODO Auto-generated method stub 
  6.         return new TeacherWork(); 
  7.     } 
  8.  

 

TeacherWorkFactory.java

 

  
  
  
  
  1. public class TeacherWorkFactory implements IWorkFactory { 
  2.  
  3.     @Override 
  4.     public Work getWork() { 
  5.         // TODO Auto-generated method stub 
  6.         return new StudentWork(); 
  7.     } 
  8.  

StudentWork.java

  
  
  
  
  1. public class StudentWork implements Work { 
  2.  
  3.     @Override 
  4.     public void work() { 
  5.         // TODO Auto-generated method stub 
  6.         System.out.println("学生做作业!"); 
  7.     } 
  8.  

TeacherWork.java

 

  
  
  
  
  1. public class TeacherWork implements Work { 
  2.  
  3.     @Override 
  4.     public void work() { 
  5.         // TODO Auto-generated method stub 
  6.         System.out.println("老师审批作业!"); 
  7.     } 
  8.  

Work.java

 

  
  
  
  
  1. public interface Work { 
  2.     void work(); 

Test.java

 

  
  
  
  
  1. public class Test { 
  2.      
  3.     public static void main(String[] args) { 
  4.          
  5.         IWorkFactory studentWorkFactory = new StudentWorkFactory(); 
  6.         studentWorkFactory.getWork().work(); 
  7.          
  8.         IWorkFactory teacherWorkFactory = new TeacherWorkFactory(); 
  9.         teacherWorkFactory.getWork().work(); 
  10.     } 

 

你可能感兴趣的:(设计模式,工厂设计模式)