设计模式之装饰者模式

来源:互联网 发布:阴谋论书籍 知乎 编辑:程序博客网 时间:2024/06/08 13:44

装饰者模式的基本组成是一个目标类和一个继承于(实现了)目标类的装饰基类,目标类可以抽象出基类和多个子类,而装饰基类可以派生出多种具体的装饰类。

目标类中指定了核心行为,装饰基类继承于目标类,装饰基类及其子类通过重写这个行为方法,给目标类添加行为。装饰者模式特殊的一点是装饰类持有的引用,也就是依赖于目标类型,通过在行为方法中调用所依赖目标类型类的方法来实现行为的传承。

目标基类:

public abstract class Person {    abstract void wear();}

目标实现类:

public class Man extends Person {    @Override    void wear() {        System.out.print("男人");    }}

装饰基类:持有目标类的引用,本身继承于目标类,重写的行为方法是调用持有目标类的行为方法。

public abstract class DecoratorPerson extends Person {    Person person;    public DecoratorPerson(Person person) {        this.person = person;    }    @Override    void wear() {        person.wear();    }}

装饰子类:继承于装饰基类,重写的行为方法是调用持有目标类的行为方法,加上自己添加的行为。

public class TShirtDecorator extends DecoratorPerson {    public TShirtDecorator(Person person) {        super(person);    }    @Override    void wear() {        super.wear();        System.out.print(" 穿T恤");    }}public class PantsDecorator extends DecoratorPerson {    public PantsDecorator(Person person) {        super(person);    }    @Override    void wear() {        super.wear();        System.out.print(" 穿长裤");    }}

测试类:

public class Test {    public static void main(String[] args){        Man man = new Man();        TShirtDecorator tShirtDecorator = new TShirtDecorator(man);        tShirtDecorator.wear();        System.out.println();        new PantsDecorator(tShirtDecorator).wear();        System.out.println();        new UnderwearDecorator(new ShoesDecorator(new PantsDecorator(new Man()))).wear();    }}

输出结果:

男人 穿T恤男人 穿T恤 穿长裤男人 穿长裤 穿鞋子 穿内裤

装饰者模式就像俄罗斯套娃,可以一层一层包装起来。
Java中的IO类即是使用装饰者模式实现的。

原创粉丝点击