22) Null Object pattern
类别:
问题:
方案:
示例:
public class NullObjectPatternDemo { public static void main(String[] args) { Animal animal; animal = getAnimal("cat"); animal.makeSound(); animal = getAnimal("dog"); animal.makeSound(); animal = getAnimal("duck"); animal.makeSound(); } public static Animal getAnimal(String type) { Animal animal; switch (type) { case "dog": { animal = new Dog(); break; } case "cat": { animal = new Cat(); break; } default: { animal = new NullAnimal(); break; } } return animal; } } interface Animal { void makeSound(); } class Dog implements Animal { public void makeSound() { System.out.println("woof!"); } } class Cat implements Animal { public void makeSound() { System.out.println("meowww.."); } } class NullAnimal implements Animal { public void makeSound() { System.out.println("..."); } }
meowww.. woof! ...
应用:
不足:(
优化:)