廣告

2015年3月17日 星期二

[java] [designPattern] Null Object Pattern

根據上一篇文章 => java-design-pattern-factory-pattern

這篇做出修改成此篇的標題,


沒列出來的class就同上篇。這篇show出做修改的部分。




NullObject.java

package com.test.nullobjectpattern;
import com.test.factorypattern.animal;
public class NullObject implements animal {

 @Override
 public void printMsg() {
  // TODO Auto-generated method stub
  System.out.println("NullObject class, means i'm null");
 }

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

 }

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

 }
}




animalFactory.java
package com.test.factorypattern;

import com.test.nullobjectpattern.NullObject;

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 {
   return new NullObject();
  }
  
 }
}




TestNullObjectPattern.java
package com.test.nullobjectpattern;

import com.test.factorypattern.animal;
import com.test.factorypattern.animalFactory;


public class TestNullObjectPattern {

 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
=========================
NullObject class, means i'm null



沒有留言:

張貼留言