zoukankan      html  css  js  c++  java
  • [大话设计模式] 第6章: 装饰模式

    装饰模式(Decorator)

    • 装饰模式:动态的给一个对象添加一些额外的职能,把所需功能按顺序串联起来并进行控制。
    • 每个要装饰的功能放在单独的类中,并让这个类包装它所要修饰的对象。当需要执行特殊行为时,客户端就可以根据需要有选择的、有顺序的使用装饰功能包装对象了。
    • 装饰模式有效的把类的核心职能和装饰功能区分开了,并且可以去除相关类中重复的装饰逻辑。

    UML类图

    • Component:定义一个对象接口,可以给这些对象动态地添加职责;
    • ConcreteComponent:定义一个具体的Component,继承自Component,重写了Component类的虚函数;
    • Decorator:维持一个指向Component对象的指针,该指针指向需要被装饰的对象;并定义一个与Component接口一致的接口;
    • ConcreteDecorator:向组件添加职责。

    装饰模式穿衣服举例

    UML类图

    #include <iostream>
    
    class Person
    {
    public:
    	virtual ~Person(){}
    	virtual void show(){ }
    };
    
    // 服饰类(Decorator)
    class Finery : public Person
    {
    public:
    	Finery(Person *p): component(p){}
    	void show() override {}
    protected:
    	Person *component;
    };
    
    class Tie : public Finery
    {
    public:
    	Tie(Person *p): Finery(p){ }
    	void show() override{
    		std::cout << "tie " << std::endl;
    		component->show();
     	}
    };
    
    class Suit : public Finery
    {
    public:
    	Suit(Person *p): Finery(p){ }
    	void show() override{
    		std::cout << "suit " << std::endl;
    		component->show();
     	}
    };
    
    class Shoes : public Finery
    {
    public:
    	Shoes(Person *p): Finery(p){ }
    	void show() override{
    		std::cout << "shoes " << std::endl;
    		component->show();
     	}
    };
    
    int main()
    {
    	Person *xc = new Person();
    	Tie    *t  = new Tie(xc);
    	Shoes  *s  = new Shoes(t);
    	s->show();
    
    	delete xc;
    	delete t;
    	delete s;
    
    	return 0;
    }
    
    /* 输出结果
    shoes
    tie
    */
    

    参考链接

    大话设计模式C++源码: https://github.com/yogykwan/design-patterns-cpp

  • 相关阅读:
    Java 数组的浅拷贝和深拷贝
    Java 传递可变参数和方法重载
    Java 数组排序
    Java 一维数组作为参数和返回值
    Java 运算符及优先级
    MySQL 由 5.7 升级为 8.0 之后,Laravel 的配置改动
    Lavarel
    Laravel框架中Blade模板的用法
    php-fpm 配置文件检测
    Laravel Blade 模板 @section/endsection 与 @section/show, @yield 的区别
  • 原文地址:https://www.cnblogs.com/moon1992/p/7267946.html
Copyright © 2011-2022 走看看