23种设计模式:装饰器模式
装饰器模式
1.介绍
概念
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
主要作用
动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
解决的问题
一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
使用场景
1、扩展一个类的功能。 2、动态增加功能,动态撤销。
(引用自菜鸟教程)
2.实现
背景
实现一个人的换装。
实现步骤
1.创建一个Person类。
public class Person {
public Person() {
}
private String name;
public Person(String name) {
this.name = name;
}
public void Show() {
System.out.println("装扮的" + name);
}
}
2.创建服装类,继承Person类。
public class Finery extends Person{
protected Person component;
//打扮
public void Decorate(Person component) {
this.component = component;
}
public void Show() {
if (component != null) {
component.Show();
}
}
}
3.创建服装类的子类。
public class TShirts extends Finery{
@Override
public void Show() {
System.out.println("大短袖");
super.Show();
}
}
public class BigTrouser extends Finery{
@Override
public void Show() {
System.out.println("垮裤");
super.Show();
}
}
4.创建测试类
public class main {
public static void main(String[] args) {
Person person = new Person("zhangsan");
System.out.println("第一种装扮:");
TShirts tShirts = new TShirts();
BigTrouser bigTrouser = new BigTrouser();
//装饰过程
tShirts.Decorate(person);
bigTrouser.Decorate(tShirts);
bigTrouser.Show();
}
}
5.运行结果
第一种装扮:
垮裤
大短袖
装扮的zhangsan