A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 825176857 中级黑马   /  2015-7-12 23:40  /  422 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  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. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马