美文网首页
GeekBand C++ 第三周

GeekBand C++ 第三周

作者: hui1429 | 来源:发表于2016-05-29 12:19 被阅读37次

    11. 组合与继承

    Object Oriented Programming,Object Oriented Design,OOP,OOD

    1. Composition(复合),表示has-a

    Composition

    实心菱形+箭头 Class A 指向 Class B,则Class A has-a Class B,即为复合关系。

    Class A has-a Class B,但是Class A没有添加任何新的功能,只是开放了部分Class B的功能,这种情况表现出了Adapter设计模式。

    Composition关系下的构造和析构

    构造由内而外
      Container的构造函数首先调用Component的default构造函数,然后才执行自己的。当需要编译器自己生成时,则需要调用default构造函数,如果不需要调用default构造函数,则需要自己在initialization list写明。

    Container::Container(...): Component(){...};
    

    析构由外而内
      Container的析构函数首先执行自己的,然后才调用Component的default析构函数。

    Container::~Container(...){ ... ~Component() };
    

    2. Delegation(委托),Composition by reference。

    Delegation

    空心菱形+箭头 Class A 指向 Class B,则Class A Delegation Class B。

    Class A 中有一个 Class B 的 pointer。任何时候,A可以调用B的方法完成任务。更恰当的表述方法是 composition by reference,它和composition的区别:

    当Class A 和Class B 是composition关系时,有了A,则同时有了B,生命周期同步。而delegation,也许先有了A,此时仅仅有了B的指针,当需要时,才去创建B,生命周期不同步。

    在delegation下,Class A 仅仅是对外的接口,而真正的实现都放在Class B中,这种写法称作pimpl(point to implantation)也称为Handle/Body。

    Class A内部的指针,不仅仅局限于指向Class B,而且当B需要变动时,Class A不用重新编译,仅仅需要重新编译Class B,所以此种写法又称为编译防火墙。

    3. Inheritance(继承),表示is-a

    Inheritance

    直线+空心三角形,由子类指向父类,表示inheritance关系。
      继承关系有三种,public,protect,private。其中public继承,表示is-a的关系。

    struct _List_node_base{
        _List_node_base* _M_next;
        _list_node_base* _M_prev;
    }:
    typeplate<typename _Tp>
    struct _List_node
        : public _List_node_base{
        _Tp _M_data;    
    };
    

    上段代码使用了public继承,因为只有数据,没有方法,表示子类继承了父类的数据。

    Inheritance关系下的构造和析构
      Class Derived 继承 Class Base,此时我们称Derived object 中含有 Base Part。

    构造由内而外
      Derived的构造函数首先调用Base的default构造函数,然后才执行自己。

    Derived::Derived(...): Base() { ... };
    

    析构由外而内
      Derived的析构函数首先执行自己,然后才调用Base的default析构函数。

    Derived::~Derived(...){ ... ~Base() };
    

    base class 的 dtor 必须是 virtual,否则会出现 undefined behavior。

    12 - 14 . 虚函数与多态

    1. Inheritance(继承) with virtual functions(虚函数)

    virtual functions分为三种:

    • non-virtual函数:你不希望derived class重新定义(override,复写)它。
    • virtual函数:你希望derived class重新定义(override,复写)它,且你对它已经有默认定义。
    • pure virtual函数:你希望derived class一定要重新定义(override,复写)它,你对它没有默认定义。
    class Shape{
    public:
        virtual void draw() const = 0;//pure virtual
        virtual void error(cosnt std::string& msg);//impure virtual
        int objectID() cosnt;//non-virtual
    };
    
    class Rectangle: public Shape{...};
    class Ellipse: public Shape{...};
    

    2. Template Method

    Template Method

    父类CDocument中的OnFileOpen()函数无法确定Serialize()中的具体行为,因此将它声明为虚函数,由子类去完成,在实际的OnFileOpen()函数执行过程中,调用的Serialize()也完全取决于子类。则对于父类CDocument中的OnFileOpen()函数,是一种在Application framework,此种写法被称为Template Method。

    对于虚函数Serialize()的调用,真正的this指针是CMyDoc类型的,当调用时,也同样是通过this指针来调用,因此当调用虚函数Serialize()时,调用的是CMyDoc的Serialize(),而非父类的Serialize()。

    #include<iostream>
    using namespace std;
    
    class CDocument{
    public:
        void OnFileOpen(){
            //这是个算法,每个cout输出代表一个实际动作
            cout << "dialog..." << endl;
            cout << "check file status..." << endl;
            cout << "open file..." << endl;
            Serialize();
            cout << "close file..." << endl;
            cout << "..." << endl;
        }
        
        virtual void Serialize(){ };
    };
    
    class CMyDoc : public CDocument{
    public:
        virtual void Serialize(){
            //只有应用程序本身才知道如何读取自己的文件(格式)
            cout << "CMyDoc::Serialize()" << endl;
        }
    };
    
    int main(){
        CMyDoc myDoc;
        myDoc.OnFileOpen();
        return 0;
    }
    

    输出结果:

    dialog...
    check file status...
    open file...
    CMyDoc::Serialize()
    close file...
    ...
    

    3. Inheritance+Composition关系下的构造和析构

    第一种情况:

    #include<iostream>
    using namespace std;
    
    class Component{
    public:
        Component(){ cout << "Component ctor called" << endl; }
        ~Component(){ cout << "Component dtor called" << endl; }
    };
    
    class Base{
    public:
        Base(){ cout << "Base ctor called" << endl; }
        virtual ~Base(){ cout << "Base dtor called" << endl; }
    };
    
    class Derived : public Base{
    public:
        Derived(){ cout << "Derived ctor called" << endl; }
        ~Derived(){ cout << "Derived dtor called" << endl; }
    private:
        Component component;
    };
    
    int main(){
        Derived *pDerived = new Derived;
        delete pDerived;
        getchar();
        return 0;
    }
    

    运行结果:

    Base ctor called
    Component ctor called
    Derived ctor called
    Derived dtor called
    Component dtor called
    Base dtor called
    
    

    由运行结果可以看出:

    • 构造由内而外,Derived首先调用了Base的默认构造函数,然后再调用Component的默认构造函数,最后调用自己的。
    • 析构由内而外,Derived首先调用自己的析构函数,然后再调用Component的析构函数,最后调用Base的析构函数。

    第二种情况:

    #include<iostream>
    using namespace std;
    
    class Component{
    public:
        Component(){ cout << "Component ctor called" << endl; }
        ~Component(){ cout << "Component dtor called" << endl; }
    };
    
    class Base{
    public:
        Base(){ cout << "Base ctor called" << endl; }
        virtual ~Base(){ cout << "Base dtor called" << endl; }
    private:
        Component component;
    };
    
    class Derived : public Base{
    public:
        Derived(){ cout << "Derived ctor called" << endl; }
        ~Derived(){ cout << "Derived dtor called" << endl; }
    };
    
    int main(){
        Derived *pDerived = new Derived;
        delete pDerived;
        getchar();
        return 0;
    }
    

    运行结果:

    Component ctor called
    Base ctor called
    Derived ctor called
    Derived dtor called
    Base dtor called
    Component dtor called
    
    

    由运行结果可以看出:

    • 构造由内而外,Derived首先调用了Component的默认构造函数,然后再调用Base的默认构造函数,最后调用自己的。
    • 析构由内而外,Derived首先调用自己的析构函数,然后再调用Base的析构函数,最后调用Component的析构函数。

    4. Delegation(委托)+Inheritance(继承)

    23个设计模式,最经典的面向对象程序设计。

    Observer

    当一个对象的改变需要同时改变其他对象的时候,而且它不知道具体有多少对象有待改变时,应该考虑使用观察者模式。
      观察者模式所做的工作其实就是在解除耦合。让耦合的双方都依赖于抽象,而不是依赖于具体。从而使得各自的变化都不会影响另一边的变化。


    Observer
    • Subject类,可翻译为主题或抽象通知者,一般用一个抽象类或者一个借口实现。它把所有对观察者对象的引用保存在一个聚集里,每个主题都可以有任何数量的观察者。抽象主题提供一个借口,可以增加和删除观察者对象。

    • Observer类,抽象观察者,为所有的具体观察者定义一个借口,在得到主题的通知时更新自己。这个借口叫做更新接口。抽象观察者一般用一个抽象类或者一个接口实现。更新接口通常包含一个Update()方法。

    • ConcreteSubject类,叫做具体主题或具体通知者,将有关状态存入具体通知者对象;在具体主题的内部状态改变时,给所有等级过的观察者发出通知。通常用一个具体子类实现。

    • ConcreteObserver类,具体观察者,实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题的状态相协调。具体观察者角色可以保存一个指向一个具体主题对象的引用。

    Composite

    组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。

    有时候又叫做部分-整体模式,它使我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。

    组合模式让你可以优化处理递归或分级数据结构。有许多关于分级数据结构的例子,使得组合模式非常有用武之地。关于分级数据结构的一个普遍性的例子是你每次使用电脑时所遇到的:文件系统。文件系统由目录和文件组成。每个目录都可以装内容。目录的内容可以是文件,也可以是目录。按照这种方式,计算机的文件系统就是以递归结构来组织的。如果你想要描述这样的数据结构,那么你可以使用组合模式Composite。


    Composite
    • 抽象构件角色(component):是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component子部件。这个接口可 以用来管理所有的子对象。(可选)在递归结构中定义一个接口,用于访问一个父部件,并在合适的情况下实现它。
    • 树叶构件角色(Leaf):在组合树中表示叶节点对象,叶节点没有子节点。并在组合中定义图元对象的行为。
    • 树枝构件角色(Composite):定义有子部件的那些部件的行为。存储子部件。在Component接口中实现与子部件有关的操作。
    • 客户角色(Client):通过component接口操纵组合部件的对象。

    Prototype

    当有类似这种需求,需要去创建未来的class,但是却不知道未来具体的calss名称。那么可以要求派生的子类,自己创建一个自己,创建出的对象,可以被框架看到的,那么就可以用来当一种原型,当框架获得原型之后,可以通过调用原型的clone函数来创建对象。

    uml图中表示类的框图,框中变量带下划线的,则为static变量。现在object name,再写type name。函数名称前带‘+’则为public,‘#’代表protect,‘-’代表private。

    类的static变量,一定谨记需要在类外定义,此时才给变量分配内存,所以称之为定义,类内部应该是声明。


    Prototype

    在上图中,破折线以下的类,是以后创建的,创建之前,破折线以上的框架是不知道这个类的名称,所以也无法创建,但是此时巧妙的使用了Prototype模式,这个问题迎刃而解。


    Prototype

    在Image类的定义中,有两个重要的纯虚函数需要子类实现,一个是returnType函数,用来返回子类的类型,用来区分不同的子类,另一个是clone函数,用来让框架使用原型来创建新的对象。findAndClone函数则返回该类型新的对象(调用clone函数)。


    Prototype3

    在Image的子类定义中,需要两个构造函数,一个是给static变量调用的,用来把原型加到框架中,而另一个构造函数是给clone函数使用的。如果只有一个默认构造函数,当调用clone函数是,则会造成原型重复加入框架,因此这里需要两个构造函数。

    相关文章

      网友评论

          本文标题:GeekBand C++ 第三周

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