Android设计模式-装饰模式

1、定义

动态给的一个对象添加额外的职责或者功能。比生成子类更为灵活。

2、适用场景

动态的扩展类的功能

3、UML图

Android设计模式-装饰模式_第1张图片

4、简单的实现

1、定义Person抽象类,需要穿衣服的抽象方法

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

2、Person实现

public class PersonClothWrapper extends Person {
    protected  Person person;

    public PersonClothWrapper(Person person) {
        this.person = person;
    }

    @Override
    public void dressed() {
        System.out.println("wear simple cloth");
    }
}

3、真正穿衣服的Boy继承Person

public class Boy extends Person {
    @Override
    public void dressed() {
        System.out.println("wear cloth");
    }
}

4、装饰者:对穿衣服进行装饰

public class ExpensiveWrapper extends PersonClothWrapper {
    public ExpensiveWrapper(Person person) {
        super(person);
    }

    @Override
    public void dressed() {
        super.dressed();
        dressedShirt();
        dressedLeather();
        dressedJean();
    }
    private void dressedShirt(){
        System.out.println("wear shirt");
    }
    private void dressedLeather(){
        System.out.println("wear shirt");
    }
    private void dressedJean(){
        System.out.println("wear shirt");
    }
}

5、测试类:

public class TestWrapper {
    public static void main(String args[]){
        Person person=new Boy();
        ExpensiveWrapper expensiveWrapper=new ExpensiveWrapper(person);
        expensiveWrapper.dressed();
    }
}

运行结果:

wear simple cloth
wear shirt
wear leather
wear jean

Ref 《Android源码设计模式解析与实战》

你可能感兴趣的:(android设计模式)