美文网首页
C++ 编程技巧与规范(四)

C++ 编程技巧与规范(四)

作者: e196efe3d7df | 来源:发表于2020-11-20 14:49 被阅读0次

    组合关系

    has-a 关系

    has-a 关系也称为 is-part-of关系。下面的定义了这种关系:

    namespace demo8 {
        class Info {
        private:
            std::string name;
            std::string address;
            int age;
        };
    
        class Human {
        public:
            Info info;
        };
    }
    

    可以是说是 Human has-a Info, 也可以说是 Info is-part-of Human。

    is-implemented-in-terms-of关系

    这种关系可以描述为:根据...实现出...。
    示例:根据multimap实现自定义map,不允许包含重复key。

    namespace demo9 {
        template<typename T, typename U>
        class smap {
        public:
            void insert(const T& key, const U& value)
            {
                if (m_map.find(key) != m_map.end())
                    return;
                m_map.insert(std::make_pair(key, value));
            }
    
            void printMap()
            {
                std::cout << "map.size() = " << size() << std::endl;
                for (auto key_value : m_map)
                {
                    std::cout << "key:" << key_value.first << ",value:" << key_value.second << std::endl;
                }
            }
    
            size_t size()
            {
                return m_map.size();
            }
        private:
            std::multimap<T, U> m_map;
        };
    
        void mainFunc()
        {
            smap<int, int> myMap;
            myMap.insert(1, 2);
            myMap.insert(2, 3);
            myMap.insert(1, 3);
            myMap.printMap();
        }
    }
    int main()
    {
        demo9::mainFunc();
    }
    

    组合关系的UML图:


    组合关系

    实心菱形框表示:如果创建了一个Human类对象(整体对象),其中就会包含一个Info类对象(成员对象),有相同的生命周期。

    委托关系

    即Delegation关系,一个类中包含指向另一个类的指针。该对象上产生的行为,会交给委托对象去执行。两者的生命周期不必相同。

    namespace demo10 {
        class A {
        public:
            void doSomething()
            {
                std::cout << "A::doSomething()" << std::endl;
            }
        };
    
        class B {
        public:
            B(A* temp) :a(temp) {}
    
            void doSomething() {
                a->doSomething();
            }
        private:
            A* a;
        };
    
        void mainFunc()
        {
            A* a = new A();
            B* b = new B(a);
    
            b->doSomething();
    
            delete b;
            delete a;
        }
    }
    
    int main()
    {
        demo10::mainFunc();
    }
    

    委托关系的UML图:


    委托关系

    相关文章

      网友评论

          本文标题:C++ 编程技巧与规范(四)

          本文链接:https://www.haomeiwen.com/subject/wjsliktx.html