黑马程序员技术交流社区

标题: 工厂模式 [打印本页]

作者: 825176857    时间: 2015-7-12 23:40
标题: 工厂模式
  1. // 抽象产品
  2. abstract class Human {
  3.     public abstract void Eat();
  4.     public abstract void Sleep();
  5.     public abstract void Beat();
  6. }

  7. // 具体产品-男人
  8. class Man extends Human {
  9.     public void Eat() {
  10.         System.out.println("Man can eat.");        
  11.     }

  12.     public void Sleep() {
  13.         System.out.println("Man can sleep.");
  14.     }

  15.     public void Beat() {
  16.         System.out.println("Man can beat doudou.");        
  17.     }

  18. }

  19. // 具体产品-女人
  20. class Female extends Human{

  21.     public void Eat() {
  22.         System.out.println("Female can eat.");   
  23.     }

  24.     public void Sleep() {
  25.         System.out.println("Female can sleep.");
  26.     }

  27.     public void Beat() {
  28.         System.out.println("Female can beat doudou.");        
  29.     }

  30. }

  31. // 简单工厂变为了抽象工厂
  32. abstract class HumanFactory {
  33.     public abstract Human createHuman(String gender) throws IOException;
  34. }

  35. // 具体工厂(每个具体工厂负责一个具体产品)  
  36. class ManFactory extends HumanFactory{  
  37.     public Human createHuman(String gender) throws IOException {  
  38.         return new Man();  
  39.     }  
  40. }  
  41. class FemaleFactory extends HumanFactory{  
  42.     public Human createHuman(String gender) throws IOException {  
  43.         return new Female();  
  44.     }  
  45. }  

  46. // 女娲造人
  47. public class Goddess {  

  48.     public static void main(String[] args) throws IOException {  
  49.         // 造个男人  
  50.         HumanFactory hf = new ManFactory();
  51.         Human h = hf.createHuman("man");
  52.         h.Eat();
  53.         h.Sleep();
  54.         h.Beat();
  55.     }
  56. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2