廣告

2015年3月16日 星期一

[java ] [Design Pattern] Factory Pattern


animal.java
package com.test.factorypattern;

public interface animal {

 void printMsg();
 void getFeet();
 void life();
}



animalFactory.java
package com.test.factorypattern;

public class animalFactory {

 public animal getAnimal(String kind){
  if (null == kind) {
   return null;
  } else if (kind.equalsIgnoreCase("dog")) {
   return new dog();
  } else if (kind.equalsIgnoreCase("cat")) {
   return new cat();
  } else if (kind.equalsIgnoreCase("bird")) {
   return new bird();
  } else {
   System.out.println("out of type");
  }
  
  
  return null;
 }
}



bird.java
package com.test.factorypattern;

public class bird implements animal{

 @Override
 public void printMsg() {
  // TODO Auto-generated method stub
  System.out.println("bird class");
 }

 @Override
 public void getFeet() {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void life() {
  // TODO Auto-generated method stub
  
 }
 

}




cat.java
package com.test.factorypattern;

public class cat implements animal {

 @Override
 public void printMsg() {
  // TODO Auto-generated method stub
  System.out.println("cat class");
 }

 @Override
 public void getFeet() {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void life() {
  // TODO Auto-generated method stub
  
 }


 
}



dog.java
package com.test.factorypattern;

public class dog implements animal{

 @Override
 public void printMsg() {
  // TODO Auto-generated method stub
  System.out.println("dog class");
 }

 @Override
 public void getFeet() {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void life() {
  // TODO Auto-generated method stub
  
 }
 


}



testFactoryPattern.java
package com.test.factorypattern;

public class testFactoryPattern {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  animalFactory animalfactory = new animalFactory();

  animal dog = animalfactory.getAnimal("dog");
  dog.printMsg();
  
  System.out.println("=========================");
  
  animal cat = animalfactory.getAnimal("cat");
  cat.printMsg();
  System.out.println("=========================");
  
  animal bird = animalfactory.getAnimal("bird");
  bird.printMsg();
  System.out.println("=========================");
  
  animal pig = animalfactory.getAnimal("pig");
  pig.printMsg();
  
 }

}



console
dog class
=========================
cat class
=========================
bird class
=========================
out of type
Exception in thread "main" java.lang.NullPointerException
 at com.test.factorypattern.testFactoryPattern.main(testFactoryPattern.java:23)


沒有留言:

張貼留言