天天看點

Design Pattern之裝飾模式

裝飾模式(Decorator),動态地給一個對象添加額外的職責,就增加功能來說,裝飾模式比生成子類更為靈活。

裝飾模式是為已有功能動态添加更多功能的一種方式,當系統需要更新的時候,是向舊的類中添加新的代碼,這些新加的代碼通常裝飾了原有類的核心職責或主要行為。如果在已有的類中添加新的字段、新的方法和新的邏輯,進而增加了主類的複雜度,而這些新加入的東西僅僅是為了滿足一些隻在某種特定情況下才會執行的特殊行為需要。裝飾模式把每個要裝飾的功能放在單獨的類中,并讓這個類包裝它所要裝飾的對象,是以,當需要執行特殊行為時,客戶代碼就可以在運作時根據需要有選擇、按順序使用裝飾。裝飾模式的優點就是把類中的裝飾功能從類中搬移出去,這樣可以簡化原有的類。

下面是裝飾模式的UML圖:

Design Pattern之裝飾模式

根據大話設計模式上的例子,利用C++對原有代碼進行重寫。代碼如下所示:

//Person.h Person抽象父類
#ifndef __PERSON_H
#define __PERSON_H

#include <stdio.h>
#include <string.h>
const int MAX_NAME_LEN = ;
class Person
{
public:
    virtual ~Person() {}
    virtual void  Show() = ;
protected:
    char m_szName[MAX_NAME_LEN];
};
#endif // !__PERSON_H
           
//Professor.h  繼承Person類
#ifndef __PROFESSOR_H
#define __PROFESSOR_H
#include "Person.h"

class Professor : public Person
{
public:
    Professor( char* szName) 
    {
        memset(m_szName, , MAX_NAME_LEN);
        if (NULL == szName)
        {
            printf("szName = NULL\n");
            memcpy(m_szName, "Professor", MAX_NAME_LEN);
        }
        else
        {
            memcpy(m_szName, szName, MAX_NAME_LEN);
        }

    }
    ~Professor() {}

    virtual void  Show()
    {
        printf("Show Professor:%s\n", m_szName);
    }
};
#endif // !__PROFESSOR_H
           
//Decorator.h  裝飾類 繼承Person類
#ifndef __DECORATOR
#define __DECORATOR
#include "Person.h"
class Decorator : public Person
{
public:
    Decorator()
    {
        m_pPerson = NULL;
    }
    ~Decorator(){ }

    void Decorate(Person *person)
    {
        if (person != NULL)
        {
            m_pPerson = person;
        }
    }

    void Show()
    {
        if (m_pPerson)
        {
            m_pPerson->Show();
        }
    }

private:
    Person *m_pPerson;
};
#endif
           
//Sneakers .h  繼承Decorator類
#ifndef __SNEAKERS_H
#define __SNEAKERS_H
#include "Decorator.h"

class Sneakers : public Decorator
{
public:
    Sneakers() {}
    ~Sneakers() {}

    void Show()
    {
        printf("球鞋\n");
        Decorator::Show();
    }

};

#endif
           

對于重複的類這裡就不再一一列舉了。

最後運作結果如下:

Design Pattern之裝飾模式

繼續閱讀