Design Pattern之裝飾模式

裝飾模式(Decorator),動態地給一個對象添加額外的職責,就增加功能來說,裝飾模式比生成子類更爲靈活。
裝飾模式是爲已有功能動態添加更多功能的一種方式,當系統需要更新的時候,是向舊的類中添加新的代碼,這些新加的代碼通常裝飾了原有類的核心職責或主要行爲。如果在已有的類中添加新的字段、新的方法和新的邏輯,從而增加了主類的複雜度,而這些新加入的東西僅僅是爲了滿足一些只在某種特定情況下才會執行的特殊行爲需要。裝飾模式把每個要裝飾的功能放在單獨的類中,並讓這個類包裝它所要裝飾的對象,因此,當需要執行特殊行爲時,客戶代碼就可以在運行時根據需要有選擇、按順序使用裝飾裝飾模式的優點就是把類中的裝飾功能從類中搬移出去,這樣可以簡化原有的類。
下面是裝飾模式的UML圖:
這裏寫圖片描述
根據大話設計模式上的例子,利用C++對原有代碼進行重寫。代碼如下所示:

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

#include <stdio.h>
#include <string.h>
const int MAX_NAME_LEN = 256;
class Person
{
public:
    virtual ~Person() {}
    virtual void  Show() = 0;
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, 0, 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

對於重複的類這裏就不再一一列舉了。
最後運行結果如下:
這裏寫圖片描述

發佈了65 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章