public interface Animal { /**所有動物都會吃*/ public void eat(); } public class Tiger implements Animal { public void eat() { System.out.println("老虎要吃飯!"); } public void run() { System.out.println("老虎要跑步!"); } } public class Parrot implements Animal { public void eat() { // TODO Auto-generated method stub System.out.println("鸚鵡要吃飯"); } public void fly() { System.out.println("鸚鵡要飛翔"); }
====================================
public interface AbstractFactory {
Tiger createTiger(); Dolphin createDolphin(); Parrot createParrot(); } ==============================
public class AsiaTiger extends Tiger {
public void run() { System.out.println("亞洲虎想跑步"); }
public void eat() { System.out.println("亞洲虎想吃飯"); } }
public class AsiaParrot extends Parrot{
public void eat() { // TODO Auto-generated method stub System.out.println("亞洲鸚鵡要吃飯"); }
public void fly() { System.out.println("亞洲鸚鵡要飛翔"); } }
public class AsiaDophin extends Dolphin { public void swim() { System.out.println("亞洲海豚想跑步"); }
public void eat() { System.out.println("亞洲海豚想吃飯"); } }
public class AsiaFactory implements AbstractFactory {
public Dolphin createDolphin() { // TODO Auto-generated method stub return new AsiaDophin(); }
public Parrot createParrot() { // TODO Auto-generated method stub return new AsiaParrot(); }
public Tiger createTiger() { // TODO Auto-generated method stub return new AsiaTiger(); }
}
===================================== public class AfricaTiger extends Tiger{ public void run() { System.out.println("非洲虎想跑步"); } public void eat() { System.out.println("非洲虎想吃飯"); } }
public class AfricaParrot extends Parrot{
public void eat() { // TODO Auto-generated method stub System.out.println("非洲鸚鵡要吃飯"); }
public void fly() { System.out.println("非洲鸚鵡要飛翔"); } }
public class AfricaDophin extends Dolphin { public void swim() { System.out.println("非洲海豚想跑步"); }
public void eat() { System.out.println("非洲海豚想吃飯"); } }
public class AfricaFactory implements AbstractFactory {
public Dolphin createDolphin() { // TODO Auto-generated method stub return new AfricaDophin(); }
public Parrot createParrot() { // TODO Auto-generated method stub return new AfricaParrot(); }
public Tiger createTiger() { // TODO Auto-generated method stub return new AfricaTiger(); }
}
=====================================================
public class Client {
/** * @param args * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException */ public static void main(String[] args) { // TODO Auto-generated method stub AbstractFactory factory = new AfricaFactory();
Tiger tiger = factory.createTiger(); tiger.eat(); tiger.run();
Dolphin dolphin = factory.createDolphin(); dolphin.eat(); dolphin.swim();
Parrot parrot = factory.createParrot(); parrot.eat(); parrot.fly();
factory = new AsiaFactory();
tiger = factory.createTiger(); tiger.eat(); tiger.run();
dolphin = factory.createDolphin(); dolphin.eat(); dolphin.swim();
parrot = factory.createParrot(); parrot.eat(); parrot.fly();
}
}
|