软件设计模式-【装饰者模式】
什么是装饰者模式
在软件开发过程中,有时想用一些现存的组件。这些组件可能只是完成了一些核心功能。但在不改变其结构的情况下,可以动态地扩展其功能。所有这些都可以釆用装饰器模式来实现。如在游戏中,我们给角色换装,本身的角色不变,针对的只是穿上了不同的衣服。
代码实现
abstract class Component {
operation();
}
class ComponentImpl extends Component {
@override
operation() {
print("我是人物组件");
}
}
abstract class Decorator extends Component {
ComponentImpl componentImpl = ComponentImpl();
otherFunction();
}
//套装1
class ConCreteDecorator1 extends Decorator {
@override
operation() {
componentImpl.operation();
otherFunction();
}
@override
otherFunction() {
print("我是套装1换装功能");
}
}
//套装2
class ConCreteDecorator2 extends Decorator {
@override
operation() {
componentImpl.operation();
otherFunction();
}
@override
otherFunction() {
print("我是套装2换装功能");
}
}