装饰模式小例

 

#include "stdafx.h"
#include "decretor.h"
#include <memory>
using namespace std;

void Test_Decorate()
{
 auto_ptr<Component> pComponent(new CreateComponentA);

 auto_ptr<Decorate> pDecorate(new BeforeDecorate);
 auto_ptr<Decorate> pDecorate2(new AfterDecorate);

 pDecorate->SetComponent(pComponent.get());
 
 pDecorate2->SetComponent(pDecorate.get())->printf();
}

int _tmain(int argc, _TCHAR* argv[])
{
 Test_Decorate();

 return 0;
}

//Decorate.h file

#include "stdafx.h"
#include "Decorate.h"

#pragma once

class Component
{
public:
 virtual void printf();
};

class CreateComponentA : public Component
{
public:
 virtual void printf();
};

class CreateComponentB : public Component
{
public:
 virtual void printf();
};

class Decorate : public Component
{
public:
 virtual void printf();

 Component* SetComponent(Component* pComponent);

protected:
 Component* m_pComponent;
};

class BeforeDecorate : public Decorate
{
public:
 virtual void printf();
};

class AfterDecorate : public Decorate
{
public:
 virtual void printf();
};

 

// decorate.h file

#include "stdafx.h"
#include "decorate.h"
#include <iostream>
#include <assert.h>


using namespace std;

void Component::printf()
{
 cout<< "I am a Base component!" <<endl;
}

void CreateComponentA::printf()
{
 cout<< "I am a A Component!" <<endl;
}

void CreateComponentB::printf()
{
 cout<< "I am a B Component!" <<endl;
}

void Decorate::printf()
{
 assert(m_pComponent);
 m_pComponent->printf();
}

Component* Decorate::SetComponent(Component* pComponent)
{
 m_pComponent = pComponent;
 return this;
}

void BeforeDecorate::printf()
{
 cout<< "Before Printf" <<endl;
 m_pComponent->printf();
}

void AfterDecorate::printf()
{
 m_pComponent->printf();
 cout<< "After Printf" <<endl;
}

你可能感兴趣的:(Class,include)