装饰模式--动态地为一个对象而不是整个类增加一些功能
画是可以挂到墙上的,画也可以放在画框里,画还可以用玻璃蒙上。
Visual.h
#include<stdio.h>
#ifndef __VISUAL_H__
#define __VISUAL_H__
class Visual
{
public:
Visual();
~Visual();
virtual void hangOn();
};
#endif
Visual.cpp
#include "Visual.h"
Visual::Visual()
{
}
Visual::~Visual()
{
}
void Visual::hangOn()
{
}
Picture.h
#include "Visual.h"
#ifndef __PICTURE_H__
#define __PICTURE_H__
class Picture :
public Visual
{
public:
Picture();
~Picture();
void hangOn();
};
#endif
Picture.cpp
#include "Picture.h"
Picture::Picture()
{
}
Picture::~Picture()
{
}
void Picture::hangOn()
{
printf("画挂在墙上\n");
}
Decorator.h
#include "Visual.h"
#ifndef __DECORATOR_H__
#define __DECORATOR_H__
class Decorator :
public Visual
{
public:
Decorator();
~Decorator();
virtual void decorate(Visual& visual);
Visual *visual;
};
#endif
Decorator.cpp
#include "Decorator.h"
Decorator::Decorator()
{
this->visual =NULL;
}
Decorator::~Decorator()
{
}
void Decorator::decorate(Visual& visual)
{
this->visual = &visual;
}
Frame.h
#include "Decorator.h"
#ifndef __FRAME_H__
#define __FRAME_H__
class Frame :
public Decorator
{
public:
Frame();
~Frame();
void hangOn();
};
#endif
Frame.cpp
#include "Frame.h"
Frame::Frame()
{
}
Frame::~Frame()
{
}
void Frame::hangOn()
{
printf("装在画框\n");
this->visual->hangOn();
}
Glass.h
#include "Decorator.h"
#ifndef __GLASS_H__
#define __GLASS_H__
class Glass :
public Decorator
{
public:
Glass();
~Glass();
void hangOn();
};
#endif
Glass.cpp
#include "Glass.h"
Glass::Glass()
{
}
Glass::~Glass()
{
}
void Glass::hangOn()
{
printf("蒙着玻璃的\n");
this->visual->hangOn();
}
把所有的头文件和源文件放到一个目录下,使用cmake
CMakeLists.txt
#project(main)
#include_directories(.)
aux_source_directory(. srclist)
#message(${srclist})
add_executable(main.exe ${srclist})
执行
cmake .
make