1. 装饰器模式
1.1 装饰器模式介绍
1.2 装饰器模式类图
传统 UML 类图
简化后的 UML 类图
1.3 装饰器模式演示
class Circle {
draw ( ) {
console. log ( '画一个圆形' )
}
}
class Decorator {
constructor ( circle) {
this . circle = circle
}
draw ( ) {
this . circle. draw ( )
this . setRedBorder ( circle)
}
setRedBorder ( circle) {
console. log ( '设置红色边框' )
}
}
let circle = new Circle ( )
circle. draw ( )
let dec = new Decorator ( circle)
dec. draw ( )
1.4 装饰器模式场景
1.4.1 ES7 装饰器
配置环境,安装插件
npm install babel-plugin-transform-decorators-legacy --save-dev
.babelrc 文件
{
"presets" : [ "es2015" , "latest" ] ,
"plugins" : [ "transform-decorators-legacy" ]
}
@testDec
class Demo {
}
function testDec ( target) {
target. isDec = true
}
alert ( Demo. isDec)
1.4.2 装饰类
@decorator
class A {
}
class A {
}
A = decorator ( A ) || A ;
function testDec ( isDec) {
return function ( target) {
target. isDec = isDec;
}
}
@testDec ( true )
class Demo {
}
alert ( Demo. isDec)
function mixins ( ... list) {
return function ( target) {
Object. assign ( target. prototype, ... list)
}
}
const Foo = {
foo ( ) {
alert ( 'foo' )
}
}
@mixins ( Foo)
class MyClass {
}
let obj = new MyClass ( ) ;
obj. foo ( )
1.4.3 装饰方法
class Person {
constructor ( ) {
this . first = 'A'
this . last = 'B'
}
@readonly
name ( ) {
return ` ${
this . first} ${
this . last} `
}
}
var p = new Persion ( )
console. log ( p. name ( ) )
function readonly ( target, name, descriptor) {
descriptor. writable = false ;
return descriptor;
}
class Math {
@log
add ( a, b) {
return a + b;
}
}
const math = new Math ( ) ;
const result = math. add ( 2 , 4 ) ;
console. log ( 'result' , result) ;
function log ( target, name, descriptor) {
var oldValue = descriptor. value;
descriptor. value = function ( ) {
console. log ( `Calling ${
name} with` , arguments) ;
return oldValue. apply ( this , arguments) ;
} ;
return descriptor;
}
1.4.4 core-decorators 插件
import {
readonly } from 'core-decorators'
class Person {
@readonly
name ( ) {
return 'zhang'
}
}
let p = new Person ( )
alert ( p. name ( ) )
p. name = function ( ) {
}
import {
deprecate } from 'core-decorators'
class Person {
@deprecate
facepalm ( ) {
}
@deprecate ( 'We stopped facepalming' )
facepalmHard ( ) {
}
@deprecate ( 'We stopped facepalming' , {
url: 'http://knowyourmeme.com/memes/facepalm' } )
facepalmHarder ( ) {
}
}
let person = new Person ( ) ;
person. facepalm ( ) ;
person. facepalmHard ( ) ;
person. facepalmHarder ( ) ;
1.5 装饰器模式设计原则验证
将现有对象和装饰器进行分离,两者独立存在
符合开放封闭原则