一 简介
装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
二 具体实例
1.要求
实现一个人的任意打扮方式,可以任意顺序,任意方式进行组合。
2.实现代码
person类:人物父类
public class Person {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public void show(){
System.out.println("装饰的" + name);
}
}
装扮展示类:继承Person,并重写show方法(重点)
public class Decorate extends Person {
private Person component;
public Decorate() {
}
//装扮
public void Decorate(Person component) {//装饰模式的重点方法
this.component = component;
}
public void show(){
if (component != null) {
component.show();
}
}
}
装扮实现类:可以任意继续扩展,用于装配
public class Shoe extends Decorate {
public void show() {
System.out.print("皮鞋 ");
super.show();
}
}
public class Tie extends Decorate {
public void show() {
System.out.print("领带 ");
super.show();
}
}
public class Trouser extends Decorate {
public void show() {
System.out.print("垮裤 ");
super.show();
}
}
public class TShirts extends Decorate {
public void show() {
System.out.print("T恤 ");
super.show();
}
}
测试类:
public class Test {
public static void main(String[] args) {
Person person = new Person("菜鸟");
TShirts tShirts = new TShirts();
Trouser trouser = new Trouser();
Tie tie = new Tie();
Shoe shoe = new Shoe();
shoe.Decorate(person);
trouser.Decorate(shoe);
tie.Decorate(trouser);
tShirts.Decorate(tie);
tShirts.show();
}
}
装扮模式:
动态的给一个对象增加一些额外的职责,就增加功能而言,装扮模式比生成子类更加灵活。有没有觉得这种模式的调用方式有点像io流中的调用方式呢,因为io流里就用的装饰模式。有兴趣的同学可以打开代码研究一下,很神奇的一种模式。
微信扫一扫
关注该公众号