装饰器模式

泪湿孤枕 提交于 2020-01-11 06:30:11

为对象添加功能,不改变其原有的结构和功能

,类似手机壳,手机功能还是正常使用,但是加了手机壳,可以防滑,美观

class Circle{
	draw(){
		console.log('画图')
	}
}
class Decorator{
	constructor(circle){
		this.circle=circle;
	}
	draw(){
		this.circle.draw();
	}
	setRedBorder(){
		this.circle.color='给图加红色的边框';
		console.log(this.circle.color);
	}
}
class Client{
	constructor(){
		/*原始的circle*/
		this.circle1=new Circle();
		/*使用装饰器生成的circle*/
		this.circle2=new Decorator(new Circle());
	}
	main(){
		this.circle1.draw();
		this.circle2.draw();
		this.circle2.setRedBorder();
	}
}

const client=new Client();
client.main();

场景:

ES7装饰器

core-decorators:装饰类,装饰方法(插件babel-plugin-transform-decorators-legacy)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!