zno2

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!
...

 

应用:

 

不足:(

 

优化:)

 

 

posted on 2023-06-09 13:37  zno2  阅读(8)  评论(0编辑  收藏  举报

导航