装饰者模式“装饰者模式”(Decorator Pattern )允许您向现有对象添加新功能,而不更改结构。 这种类型的设计模式是结构模式,是作为现有类的包。
此模式创建包装原始类的装饰类,并在保持类方法签名完整性的同时提供其他功能。
*意图: **动态为一个对象添加附加责任。 要添加功能,装饰模式比生成子类更灵活。
类图
类图示例
代码//DrinkComponent接口package test01; 公共语音操作(; } package test01; publicclasswatercomponentimplementsdrinkcomponent { @ overridepublicvoidoperation ()//todo auto-generatedmethodstubsystion publicclassdrinkdecoratorimplementsdrinkcomponent { drinkcomponentcomponent; publicdrinkdecorator (drinkcomponentcomponent ) {super; this.component=component; } @ overridepublicvoidoperation ((/todo auto-generatedmethodstub )//sugardecorator.javapackagetest 01; publicclasssugardecoratorextendsdrinkdecorator { publicsugardecorator (drinkcomponentcomponent ) super ) component; //todo auto-generatedconstructorstub } public void operation () { component.operation; System.out.print (,with sugar ); }//tea decorator.javapackagetest 01; publicclassteadecoratorextendsdrinkdecorator { publicteadecorator (drinkcomponentcomponent ) super ) component; //todo auto-generatedconstructorstub } public void operation () { component.operation; System.out.print (,with Tea ); }} //MainClass.javapackage test01; 公共类主类{公共类(string [ ] args )//todo auto-generatedmethodstubwatercomponentwater=newwate 白开水里加糖。 teadecoratortea=newteadecorator (sugar; 在加糖的白开水里加入茶叶。 tea.operation(/*茶和加糖的白开水诞生了。 你也可以自由地在白开水里放你喜欢的东西。 在不引起类泛滥的情况下继承DrinkDecorator就可以了。 */}输出