4.7 引入NULL对象

【1】引入NULL对象范例

Book.h

 1 #ifndef _BOOK_H
 2 #define _BOOK_H
 3 
 4 #include <string>
 5 using namespace std;
 6 
 7 class INULLOperator
 8 {
 9 public:
10     virtual bool isNull() = 0;
11 };
12 
13 class Book : public INULLOperator
14 {
15 public:
16     Book();
17     Book(int id, string name, double dprice);
18 
19     bool isNull();
20     string getName();
21     double getPrice();
22     static Book* createNullBook();
23 
24 private:
25     int m_nID;
26     string m_strName;
27     double m_dPrice;
28 };
29 
30 class NullBook : public Book
31 {
32 public:
33     bool isNull();
34 };

Book.cpp

 1 #include "Book.h"
 2 
 3 Book::Book() 
 4 {}
 5 
 6 Book::Book(int id, string name, double dprice)
 7     : m_nID(id)
 8     , m_strName(name)
 9     , m_dPrice(dprice)
10 {}
11 
12 bool Book::isNull() 
13 { 
14     return false; 
15 }
16 
17 string Book::getName() 
18 { 
19     return m_strName; 
20 }
21 
22 double Book::getPrice() 
23 { 
24     return m_dPrice; 
25 }
26 
27 Book* Book::createNullBook()
28 {
29     return (new NullBook());
30 }
31 
32 bool NullBook::isNull()
33 {
34     return true;
35 }

main.cpp

 1 #include "Book.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 class BookService
 6 {
 7 public:
 8     Book* getBook(int nId)
 9     {
10         if (nId < 0)
11         {
12             return Book::createNullBook();
13         }
14         return (new Book(nId, "Design Pattern", 100));
15     }
16 };
17 
18 void main()
19 {
20     BookService *pBService = new BookService();
21     Book *pBook = pBService->getBook(-1);
22     if (pBook->isNull())
23     {
24         cout << "not found. " << endl;
25     }
26     else
27     {
28         cout << "name :: " << pBook->getName() << endl;
29         cout << "price :: " << pBook->getPrice() << endl;
30     }
31 }

【2】总结

当你需要再三检查某个对象是否为NULL。将NULL值替换为NULL对象。

Good Good Study, Day Day Up.
顺序 选择 循环 总结

原文地址:https://www.cnblogs.com/Braveliu/p/7364804.html