Intent

Motivation

Decorator Patterns :装饰模式可真是换皮肤,给产品除核心职责外添加其他特性,最好用的模式了,比如男生每月换个发型用装饰模式就很奈斯-LMLPHP
Decorator Patterns :装饰模式可真是换皮肤,给产品除核心职责外添加其他特性,最好用的模式了,比如男生每月换个发型用装饰模式就很奈斯-LMLPHP

Structure

Decorator Patterns :装饰模式可真是换皮肤,给产品除核心职责外添加其他特性,最好用的模式了,比如男生每月换个发型用装饰模式就很奈斯-LMLPHP

Consequences

  1. More flexibility than static inheritance.
  2. Avoids feature-laden classes high up in the hierarchy.
  3. A decorator and its component aren’t identical.
  4. 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;
}

Decorator Patterns :装饰模式可真是换皮肤,给产品除核心职责外添加其他特性,最好用的模式了,比如男生每月换个发型用装饰模式就很奈斯-LMLPHP

11-19 09:42