1.泡妞与设计模式(二)合成模式

合成模式

合成模式:合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树结构表示出来。合成模式使得客户端把一个个单独的成分对象和由他们复合而成的合成对象同等看待。

Mary今天过生日。“我过生日,你要送我一件礼物。”“嗯,好吧,去商店,你自己挑。”“这件T恤挺漂亮,买,这条裙子好看,买,这个包也不错,买。”“喂,买了三件了呀,我只答应送一件礼物的哦。”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻烦你包起来。”“……”,MM都会用Composite模式了,你会了没有?

 

完整代码

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <Windows.h>

#include <atlstr.h>
#include <sphelper.h>
#include <sapi.h>
#include <compstui.h>
#include <string.h>
//语音函数
#pragma comment(lib,"sapi.lib")
#pragma comment(lib,"comsupp.lib")
#pragma comment(lib,"ole32.lib")

//函数指针
void(*p)(wchar_t *str) = NULL;

//语音说出来
void speak(wchar_t *str)
{
    ISpVoice *pVoice = NULL;
    ::CoInitialize(NULL);
    //获取ISpVoice接口
    long hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
    if (FAILED(hr))
    {
        MessageBox(NULL, "CoCreateInstance失败!", "错误", 0x10010);
        return;
    }
    hr = pVoice->Speak(str, 0, NULL);
    pVoice->Release();
    pVoice = NULL;
    //千万不要忘记
    ::CoUninitialize();
}

//输出到屏幕
void print(wchar_t *str)
{
    wprintf(L"%ls", str);
}

//对话框显示
void show(wchar_t *str)
{
    MessageBoxW(NULL, L"i love you", str, NULL);
}

//接口固定,对一串文字执行不同的操作
void factory(void(*pfun)(wchar_t *str),wchar_t *pstr)
{
    p = pfun;
    p(pstr);
}

//合成模式
void merge(void(**pp)(wchar_t *str), int n,wchar_t *str)
{
    for (int i = 0; i < n; i++)
    {
        (*(pp+i))(str);
    }
}


void main()
{
    setlocale(LC_ALL, "zh-CN");

    void (*pp[3])(wchar_t *str) = { print,show,speak };
    int n = sizeof(pp) / sizeof(void *);
    while (1)
    {
        //factory(show, L"老板来四个鸡腿");
        merge(pp,n,L"i love you");
        system("pause");
    }

    system("pause");
}

 

posted @ 2018-03-08 23:26  喵小喵~  阅读(168)  评论(0编辑  收藏  举报