装饰模式 :装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。 装饰模式是一种 结构型模式 主要角色 : (1)抽象构件(Component)角色:给出一个抽象接口,以规范准备
装饰模式 :装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
装饰模式是一种 结构型模式
主要角色 :
(1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
(2)具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
(3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
(4)具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。
uml类图如下所示:
下面是php实现的一个实例:
<?php /* * 装饰模式:在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。 * * 角色 * 抽象构件(Component)角色:定义一个对象接口,以规范准备接收附加职责的对象,从而可以给这些对象动态地添加职责。 * 具体构件(Concrete Component)角色:定义一个将要接收附加职责的类。 * 装饰(Decorator)角色:持有一个指向Component对象的指针,并定义一个与Component接口一致的接口。 * 具体装饰(Concrete Decorator)角色:负责给构件对象增加附加的职责。 */ //1抽象构件角色 abstract class drink{ abstract function showprice(); } //具体构件角色 class coffee extends drink{ public $name = '咖啡'; public $price = '10'; public function showprice(){ echo $this->name.' '; echo $this->price.'元'; } } //生成对象。 $coffee = new coffee(); //$coffee->showprice(); //上面我已经生成了一个对象,现在已经在线上运行 //但是我想动态的为coffee对象添加功能,而不改变原有的类和继承关系,怎么办? //装饰模式 //装饰角色 class decretor extends drink{ public $drink; public function __construct(drink $drink){//包装了对象哦 $this->drink = $drink; } public function showprice(){//实现对象原有功能, $this->drink->showprice(); $this->add();//新增功能 } public function add(){ } } //具体装饰角色 class suger extends decretor{ public $price = 1.5; public $name = '加糖'; public function add(){ echo $this->name.' '.$this->price; echo ' 一共'.($this->drink->price+$this->price).'元'; } } $suger = new suger($coffee); $suger->showprice(); ?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
