核心概念
装饰模式的核心概念就是 动态
给一个对象添加一些额外的功能。
具体来说就是针对业务核心类进行功能拆解,即核心业务类只保留核心业务功能,其他 装饰
性的功能拆分为单独的一个类。当我们需要为核心类添加装饰功能时,我们可以选择性地、顺序性的来来业务主类对象添加装饰类。
UML 图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VwO0LdBx-1687059982506)(./装饰模式.png “装饰模式”)]
具体实例
abstract class Component {
private count: number = 0;
public abstract Operation(): void;
public addCount(val: number) {
this.count += val;
}
public getCount(): number {
return this.count;
}
}
class ConcreteComponent extends Component {
public Operation(): void {
this.addCount(10);
console.log("实现 Component 的具体方法");
}
}
abstract class Decorator extends Component {
protected component: Component | undefined;
public setComponent(component: Component) {
this.component = component;
}
public Operation(): void {
if (this.component) {
this.component.Operation();
}
}
}
class ConcreteDecoratorA extends Decorator {
private addedState: string = "";
public Operation(): void {
super.Operation();
this.addedState = "新的状态值";
console.log(`具体的装饰类A, count = ${this.component?.getCount()}`);
}
public getAddedState(): string {
return this.addedState;
}
}
class ConcreteDecoratorB extends Decorator {
public Operation(): void {
super.Operation();
this.getAgeInfo();
console.log("具体的装饰类B");
}
private getAgeInfo(): void {
console.log("调用了装饰类B的私有方法");
}
}
const c: ConcreteComponent = new ConcreteComponent();
const cdA: ConcreteDecoratorA = new ConcreteDecoratorA();
const cdB: ConcreteDecoratorB = new ConcreteDecoratorB();
cdA.setComponent(c);
cdB.setComponent(cdA);
cdB.Operation();
总结
通过上述的简单例子我们可以看到,我们可以在基类中添加核心业务变量和方法,并且可以再装饰类中调用基类中对外暴露的变量和方法,这样我们就可以按照业务逻辑顺序加载装饰类,从而对基类的业务进行灵活的扩展。