Skip to content

空对象模式 (Null Object Pattern)

什么是空对象模式?

空对象模式(Null Object Pattern)是一种行为型设计模式,它为接口提供一个默认实现:一个什么都不做、只返回无害值的对象。你的代码不再交出空指针,而是交出这个空对象,对它的每一次调用都是安全的。

核心思想:把"没有对象"换成"有一个什么都不做的对象"——客户端不再问这个对象在不在。

为什么需要空对象模式?

问题场景

假设你有一个工厂,它把一个类型名字变成一只动物。工厂不认识的名字根本没有对应的动物,于是工厂返回空指针,每个调用方都必须检查它:

// Problem: the factory returns null, and every call site has to check
class Animal {
public:
    virtual ~Animal() = default;
    virtual std::string speak() const = 0;
    virtual std::string move() const = 0;
};

class AnimalFactory {
public:
    static std::shared_ptr<Animal> create(const std::string& type) {
        if (type == "dog") return std::make_shared<Dog>();
        if (type == "cat") return std::make_shared<Cat>();
        return nullptr;  // an unknown type: no animal at all
    }
};

// Every client repeats the same check
void report(const std::string& type) {
    auto animal = AnimalFactory::create(type);
    if (!animal) {
        std::cout << "  " << type << ": (no animal)\n";
        return;
    }
    std::cout << "  " << type << ": " << animal->speak() << " - " << animal->move() << "\n";
}

问题: 1. 每个调用点都在重复同样的检查 2. 漏掉一次检查就是运行时的崩溃 3. "没有动物"这件事由每个客户端各自决定,而不是集中在一处

解决方案

给接口配一个空对象:一个对每次调用都给出什么都不做的默认值的类。工厂交出这个对象而不是空指针,于是客户端可以直接使用这只动物,而不必再问它在不在:

// Solution: the factory never returns null, it returns a null object
class NullAnimal : public Animal {
public:
    std::string speak() const override { return "(silence)"; }
    std::string move() const override { return "(nothing)"; }
};

class AnimalFactory {
public:
    static std::shared_ptr<Animal> create(const std::string& type) {
        if (type == "dog") return std::make_shared<Dog>();
        if (type == "cat") return std::make_shared<Cat>();
        return std::make_shared<NullAnimal>();  // never null
    }
};

// The client no longer checks
void report(const std::string& type) {
    auto animal = AnimalFactory::create(type);
    std::cout << "  " << type << ": " << animal->speak() << " - " << animal->move() << "\n";
}

优点: 1. 客户端不再测试空指针 2. "什么都没有"由一处决定——工厂 3. 新的客户端不会把检查写错

这个模式适合"这里本来就没有东西"属于正常结果的场景,比如一次查空的查找。它不适合缺席本身就是失败的场景:缺失的文件或被拒绝的请求必须作为失败上报,而不是被一个什么都不做的默认值悄悄吞掉。

模式结构

                    ┌─────────────┐
                    │   Animal    │
                    │  (接口)     │
                    └──────┬──────┘
                           │
           ┌───────────────┼───────────────┐
           │               │               │
    ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
    │    Dog      │ │     Cat      │ │  NullAnimal │ ← 空对象
    │  (真实)     │ │  (真实)     │ │   (空)      │
    └─────────────┘ └─────────────┘ └─────────────┘
           │               │               │
           └───────────────┼───────────────┘
                           │
                    ┌──────▼──────┐
                    │    Client   │ ← 从不检查空指针
                    └─────────────┘

代码实现

1. 定义接口

客户端针对这个接口编程,接口带有虚析构函数,这样多态指针才能被安全地删除。

#include <iostream>
#include <memory>
#include <string>
#include <vector>

namespace null_object {

// The interface the client codes against.
class Animal {
public:
    virtual ~Animal() = default;
    virtual std::string speak() const = 0;
    virtual std::string move() const = 0;
};

} // namespace null_object

2. 实现真实对象

真实对象做真正的工作,只有空对象被允许什么都不做。

namespace null_object {

// Real animals.
class Dog : public Animal {
public:
    std::string speak() const override { return "Woof!"; }
    std::string move() const override { return "Runs"; }
};

class Cat : public Animal {
public:
    std::string speak() const override { return "Meow!"; }
    std::string move() const override { return "Prowls"; }
};

class Bird : public Animal {
public:
    std::string speak() const override { return "Tweet!"; }
    std::string move() const override { return "Flies"; }
};

} // namespace null_object

3. 实现空对象

空对象上的每一次调用都是安全的:它返回一个无害的默认值,而不是做任何事情。

namespace null_object {

// The null object: every call is a safe no-op with a harmless default.
class NullAnimal : public Animal {
public:
    std::string speak() const override { return "(silence)"; }
    std::string move() const override { return "(nothing)"; }
};

} // namespace null_object

4. 让工厂返回空对象

工厂是唯一决定"什么都没有"是什么意思的地方,它永远不返回空指针。

namespace null_object {

// The factory never hands back a null pointer: an unknown type gives the
// null object instead.
class AnimalFactory {
public:
    static std::shared_ptr<Animal> create(const std::string& type) {
        if (type == "dog") {
            return std::make_shared<Dog>();
        }
        if (type == "cat") {
            return std::make_shared<Cat>();
        }
        if (type == "bird") {
            return std::make_shared<Bird>();
        }
        return std::make_shared<NullAnimal>();
    }
};

} // namespace null_object

5. 编写客户端

客户端直接调用这只动物,而不问它在不在。同一个客户端在每个调用点都加上检查依然能工作,但那段检查已经成了模式让它们变得多余的废代码。

// The client: it never asks whether the animal is there.
void show(const null_object::Animal& animal, const std::string& type) {
    std::cout << "  " << type << ": " << animal.speak() << " - " << animal.move() << "\n";
}

int main() {
    std::cout << "=== Null Object Pattern Demo ===\n\n";

    const std::vector<std::string> types = {"dog", "cat", "bird", "fish"};

    std::cout << "-- the client, with no null check --\n";
    for (const std::string& type : types) {
        auto animal = null_object::AnimalFactory::create(type);
        show(*animal, type);
    }

    std::cout << "\n-- the same client, with a null check at every call site --\n";
    for (const std::string& type : types) {
        auto animal = null_object::AnimalFactory::create(type);
        if (animal == nullptr) {  // the check the pattern removes
            std::cout << "  " << type << ": (no animal)\n";
            continue;
        }
        show(*animal, type);
    }

    std::cout << "\n-- the null object is an ordinary object --\n";
    auto unknown = null_object::AnimalFactory::create("fish");
    const bool is_null_animal =
        dynamic_cast<null_object::NullAnimal*>(unknown.get()) != nullptr;
    std::cout << "  an unknown type gives a NullAnimal: "
              << (is_null_animal ? "yes" : "no") << "\n";
    std::cout << "  it still answers every call: "
              << unknown->speak() << " / " << unknown->move() << "\n";

    std::cout << "\n=== Demo Complete ===\n";
    return 0;
}

null-object-pattern 项目把同样的代码放进一个头文件,并在其之上加了一套测试。

现代 C++ 实现

一个共享实例

空对象不持有任何状态,因此一个实例就能服务所有客户端,工厂也不必为每次查找都新分配一个。

// The null object holds no state, so a single instance serves everyone.
std::shared_ptr<null_object::Animal> null_animal() {
    static const std::shared_ptr<null_object::Animal> shared =
        std::make_shared<null_object::NullAnimal>();
    return shared;
}

默认值可配置的空对象

空对象不必是固定的一组字符串:它可以把要返回的默认值作为构造函数参数接收。

class ConfigurableNullAnimal : public null_object::Animal {
public:
    ConfigurableNullAnimal(std::string speak_text, std::string move_text)
        : speak_(std::move(speak_text)), move_(std::move(move_text)) {}

    std::string speak() const override { return speak_; }
    std::string move() const override { return move_; }

private:
    std::string speak_;
    std::string move_;
};

作为默认成员值的空对象

这件事并不需要工厂。作为成员的空对象永远不为空,所以使用它的代码永远不用检查它。

class NullLogger {
public:
    void log(const std::string&) const {}  // the do-nothing default
};

class Report {
public:
    void print() { logger_.log("report printed"); }

private:
    NullLogger logger_;  // never null, so nobody has to check it
};

与相关模式的区别

模式 区别
代理模式 代理把每次调用转发给真实对象;空对象背后没有真实对象
std::optional optional 把空值的情况推给调用方,由调用方处理;空对象把默认值留在对象内部
单例模式 单例共享的是一个真实类的实例;空对象共享的是一个什么都不做的类的实例
策略模式 策略改变客户端的行为;空对象只改变"没有东西可处理"时的结果

最佳实践

1. 只在一个地方返回空对象

只要工厂的每一条出口都交回一个可用的对象,这个模式就成立。

// Recommended: the factory is the only place that decides
std::shared_ptr<Animal> create(const std::string& type) {
    if (type == "dog") return std::make_shared<Dog>();
    if (type == "cat") return std::make_shared<Cat>();
    return std::make_shared<NullAnimal>();  // the one null-free exit
}

// Not recommended: a second path that hands out a raw null
std::shared_ptr<Animal> create_unchecked(const std::string& type) {
    if (type == "dog") return std::make_shared<Dog>();
    return nullptr;  // the pattern breaks here
}

2. 让默认值诚实

默认值应该说明发生了什么,而不是假装发生过什么。

// Recommended: the default says what happened
class NullAnimal : public Animal {
public:
    std::string speak() const override { return "(silence)"; }
    std::string move() const override { return "(nothing)"; }
};

// Not recommended: the default pretends the animal was there
class LyingNullAnimal : public Animal {
public:
    std::string speak() const override { return "Woof!"; }
    std::string move() const override { return "Runs"; }
};

3. 把空对象留给"缺席"场景

空对象的意思是"这里没有东西"。当缺席本身就是失败时,就应该报告这个失败,否则它会消失在一个沉默的默认值里。

// Recommended: the null object stands for an ordinary empty result
auto animal = AnimalFactory::create("fish");
std::cout << animal->speak();  // "(silence)"

// Not recommended: a failure is turned into an ordinary empty result
auto report = load_report("missing.txt");
report->render();  // an empty report instead of a loud failure

常见陷阱

陷阱 1:空对象吞掉了真正的错误

如果每一种失败都返回空对象,客户端就分不清"未知的类型"和"坏掉的系统"。

// Not recommended: a broken system looks exactly like an unknown type
std::shared_ptr<Animal> create_or_null(const std::string& type) {
    if (type == "dog") return std::make_shared<Dog>();
    if (!registry_ready()) {
        return std::make_shared<NullAnimal>();  // the failure is hidden
    }
    return std::make_shared<NullAnimal>();
}

// Recommended: the failure is reported, the null object only means "nothing"
std::shared_ptr<Animal> create_or_fail(const std::string& type) {
    if (!registry_ready()) {
        throw std::runtime_error("the animal registry is not ready");
    }
    if (type == "dog") return std::make_shared<Dog>();
    return std::make_shared<NullAnimal>();
}

陷阱 2:空对象返回了撒谎的值

一个声称工作已经完成的默认值,会把空对象本该暴露的问题藏起来。

class Writer {
public:
    virtual ~Writer() = default;
    virtual bool write(const std::string& text) = 0;
};

// Not recommended: the default pretends the write succeeded
class LyingNullWriter : public Writer {
public:
    bool write(const std::string&) override { return true; }
};

// Recommended: the default says that nothing was written
class NullWriter : public Writer {
public:
    bool write(const std::string&) override { return false; }
};

陷阱 3:空对象被切片

空对象和别的派生类一样,所以按值交出它会把它削减成基类,从而破坏它。

// Not recommended: returning the null object by value slices it
Animal sliced_null_animal() {
    return NullAnimal();  // only the Animal part survives
}

// Recommended: hand it out through a pointer, like every other animal
std::shared_ptr<Animal> null_animal_ptr() {
    return std::make_shared<NullAnimal>();
}

示例

这个主题的可运行版本:

总结

空对象模式的核心要点:

  • 适用场景:查找可能合法地查不到东西,而客户端代码本来要在每个地方重复同样的空指针检查
  • 核心优点:客户端不再测试空指针、一处决定"什么都没有"的含义、新的客户端不会把检查写错
  • 实现要点:让工厂交出空对象、让默认值诚实、让空对象保持无状态
  • 常见陷阱:吞掉真正的错误、撒谎的默认值、空对象被切片
  • 相关文档:策略模式、工厂方法模式、代理模式
  • 陷阱文章:悬垂指针、对象切片、内存泄漏

记住:空对象模式的关键是一个能回答每次调用的默认值——给接口一个什么都不做的对象,客户端就不必再问这个对象在不在。