模式定义装饰模式(Decorator Pattern )通过向对象动态添加“附加角色”(Responsibility ),装饰模式在添加对象功能时比生成子类实现时更灵活。 别名也称为包装器(Wrapper ),与适配器模式别名相同,但适用于各种情况。 有些翻译把装饰模式称为油漆工模式。 这是对象结构模式。
主要是对原始对象的功能增强
架构结构装饰模式包括以下角色:
组件:抽象组件
ConcreteComponent:的具体组件
Decorator:抽象装饰类
ConcreteDecorator:具体装饰类
适用的场景可以在以下情况下使用装饰模式:
1 .以动态和透明的方式将责任添加到每个对象,而不影响其他对象。
2 .需要动态地向一个对象中添加功能,这些功能也可以动态地取消。
3 .不能采用继承方式扩展系统,或者采用继承不利于系统扩展和维护的。 无法采用继承时主要有两类。 第一,系统中存在大量独立的扩展,产生大量子类以支持每个组合,子类数量呈爆炸式增长。 第二,因为类定义不能继承(例如,final类)。
代码实现packagemainimport(fmt )/idrawidrawtypeidrawinterface (draw ) (string )/square正方形typesquarestruct (drawdrawdring ) draw string { return ' thisisasquare '//color square彩色正方形typecolorsquarestruct { squareidrawcolorstring }//newcolorsquarenewcolorsquarefuncnewcolorsquare { squareidraw, colorstring } color square { returncolorsquare } color 3360 color square : square }//drawdrawfunc (ccolor square ) draw ) color is ' c.color}//主要增强原始对象功能的func main ((result :=new color square (new ) square ),' red ' ).draw (fmt )