package com.deng.DesignPattern.Factory03; interface Person{ public void eat(); public void talk(); } //男人 class Man implements Person{ public void eat() { System.out.println("男人在吃东西..."); } public void talk() { System.out.println("男人在说话..."); } } //女人 class Woman implements Person{ public void eat(){ System.out.println("女人在吃东西..."); } public void talk(){ System.out.println("女人在说话..."); } } interface Animal{ public void eat(); public void sleep(); } //公牛 class Bull implements Animal{ public void eat() { System.out.println("Bull 在吃东西..."); } public void sleep() { System.out.println("Bull 在睡觉..."); } } //母牛 class Cow implements Animal{ public void eat() { System.out.println("Cow 在吃东西..."); } public void sleep() { System.out.println("Cow 在睡觉..."); } } interface NWFactory{ public Person getPerson(String type); public Animal getAnimal(String type); } //阳绳造男人和公牛 class YangSheng implements NWFactory{ Man m = null; Bull b = null; public Bull getAnimal(String type) { try { b = (Bull)Class.forName("com.deng.DesignPattern.Factory03."+type).newInstance(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return b; } public Man getPerson(String type) { try { m= (Man)Class.forName("com.deng.DesignPattern.Factory03."+type).newInstance(); } catch (Exception e) { e.printStackTrace(); } return m ; } } //阴绳造女人和母牛 class YinSheng implements NWFactory{ Cow c = null; Woman w = null; public Cow getAnimal(String type) { try { c = (Cow)Class.forName("com.deng.DesignPattern.Factory03."+type).newInstance(); } catch (Exception e) { e.printStackTrace(); } return c; } public Woman getPerson(String type) { try { w = (Woman)Class.forName("com.deng.DesignPattern.Factory03."+type).newInstance(); } catch (Exception e) { e.printStackTrace(); } return w; } } public class FactoryDemo03 { public static void main(String[] args) { //造男人和公牛 YangSheng ys = new YangSheng(); //ys为阳绳 YinSheng ys1 = new YinSheng(); //ys1为阴绳 Person p1= ys.getPerson("Man"); p1.eat(); p1.talk(); Animal a1 =ys.getAnimal("Bull"); a1.eat(); a1.sleep(); Person p2 = ys1.getPerson("Woman"); p2.eat(); p2.talk(); Animal a2 = ys1.getAnimal("Cow"); a2.eat(); a2.sleep(); } }