Intent
Motivation
Structure
Consequences
- More flexibility than static inheritance.
- Avoids feature-laden classes high up in the hierarchy.
- A decorator and its component aren’t identical.
- Lots of little Objects.
// DesignPattern.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <share.h>
#include <list>
#include <vector>
#include <memory>
class VisualComponent {
public:
VisualComponent() {
}
virtual void Draw() {
}
virtual void Resize() {
}
};
class TextView : public VisualComponent {
public:
TextView() {
}
virtual void Draw() {
std::cout << __FUNCTION__ << std::endl;
}
virtual void Resize() {
std::cout << __FUNCTION__ << std::endl;
}
};
class Decorator : public VisualComponent {
public:
Decorator() {}
// 此处有个坑:最开始参数写成 VisualComponent*
// 报错error: "没有重载函数可以转换所有参数类型 "
Decorator(std::shared_ptr<VisualComponent> VComponent) {
}
virtual void Draw() {
std::cout << __FUNCTION__ << std::endl;
if (component_ != nullptr)
component_->Draw();
}
virtual void Resize() {
std::cout << __FUNCTION__ << std::endl;
if (component_ != nullptr)
component_->Resize();
}
private:
std::shared_ptr<VisualComponent> component_;
};
class BorderDecorator : public Decorator {
public:
BorderDecorator(std::shared_ptr<VisualComponent> VComponent, int borderWidth) {
}
virtual void Draw() {
Decorator::Draw();
DrawBorder(width_);
}
private:
void DrawBorder(int) {
std::cout << __FUNCTION__ << std::endl;
}
private:
int width_;
};
class ScrollDecorator : public Decorator {
public:
ScrollDecorator(std::shared_ptr<VisualComponent> VComponent) {
}
virtual void Draw() {
Decorator::Draw();
addedState();
}
private:
void addedState() {
std::cout << __FUNCTION__ << std::endl;
}
};
class Window {
public:
Window(){}
void SetContents(std::shared_ptr<VisualComponent> contents) {
std::cout << __FUNCTION__ << std::endl;
contents->Draw();
contents->Resize();
}
};
int main()
{
std::shared_ptr<Window> window = std::make_shared<Window>();
auto text_view = std::make_shared<TextView>();
auto scroll_decorator = std::make_shared<ScrollDecorator>(text_view);
auto border_decorator = std::make_shared<BorderDecorator>(scroll_decorator, 1);
window->SetContents(border_decorator);
return 0;
}