设计模式学习笔记——装饰模式

定义


装饰模式——动态地将责任附加到对象上。就增加功能来说,装饰模式相比生成子类更为灵活。

使用场景


  • 需要透明且动态地扩展类的功能时。
  • 需要去除相关类中重复的装饰逻辑时。

UML类图


设计模式学习笔记——装饰模式_第1张图片
  • Component:是定义的一个对象接口,可以给这些对象动态地添加职责。
  • ConcreteComponent:组件具体实现类。该类是Component类的基本实现,也是我们装饰的具体对象。
  • Decorator:装饰抽象类。其内部一定要有一个指向组件对象的引用。
  • ConcreteComponentA:具体的装饰者实现类。

例子


人的着装就是人的装饰,下面用小美着装打扮来演示装饰模式:
人着装接口:

interface People {
    void dress();
}

小美:

public class XiaoMei implements People {
    private String name;

    public XiaoMei(String name) {
        this.name = name;
    }

    @Override
    public void dress() {
        System.out.print(name);
    }
}

着装类:

public class Finery implements People {
    protected People people;

    public Finery(People people) {
        this.people = people;
    }

    @Override
    public void dress() {
        if (people != null) {
            people.dress();
        }
    }
}

具体着装类:

public class WhiteTShirt extends Finery {
    public WhiteTShirt(People people) {
        super(people);
    }

    @Override
    public void dress() {
        super.dress();
        System.out.print(" 上身穿简单白T恤 ");
    }
}

public class Tights extends Finery {
    public Tights(People people) {
        super(people);
    }

    @Override
    public void dress() {
        super.dress();
        System.out.print(" 下半身紧身小脚裤 ");
    }
}

public class NickShoes extends Finery {

    public NickShoes(People people) {
        super(people);
    }

    @Override
    public void dress() {
        super.dress();
        System.out.print(" 脚穿Nike鞋 ");
    }
}

客户端调用:

public class Test {

    public static void main(String[] args) {
        XiaoMei xiaoMei = new XiaoMei("小美");

        WhiteTShirt wt = new WhiteTShirt(xiaoMei);
        Tights ts = new Tights(wt);
        NickShoes ns = new NickShoes(ts);
        ns.dress();
    }
}

输出结果:

小美 上身穿简单白T恤 下半身紧身小脚裤 脚穿Nike鞋

这只是一个简单的例子,你可以灵活的实现其他的具体着装类,在使用的时候替换。

总结


装饰模式的优点就是把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开,而且可以有效的去除相关类中重复的装饰逻辑。

本博文为读书笔记:
《Head First 设计模式》
《大话设计模式》
《Android源码设计模式解析与实战》

你可能感兴趣的:(设计模式学习笔记——装饰模式)