装饰者模式

  最近学习设计模式,跟着《大话设计模式》和《Head First设计模式》两本书边练边学,学到装饰者模式的时候,死活理解不了装饰者模式是怎么调用的,最后搜索了很多资料,才搞明白装饰者模式是怎么层层调用的。

下面先贴下代码

1.WearClothes

/**
 * 穿衣服
 * 装饰者模式中的Component,定义一个抽象接口,用于统一具体对象和wear类型一致。
 * @author huanglg
 *
 */
public abstract class WearClothes {

    public String action(){
        return "穿衣服的操作";
    }
}
View Code

2.Tom

/**
 * 具体穿衣服的人
 * 装饰者模式中的ConcreateComponent,定义一个具体对象。
 * @author huanglg
 *
 */
public class Tom extends WearClothes {

    @Override
    public String action() {
        return "汤姆刚刚起床,准备穿衣服。";
    }

    
}
View Code

3.Clothes

/**
 * 衣服抽象类
 * 装饰者模式中的Decorator,装饰抽象类。
 * @author huanglg
 *
 */
public abstract class Clothes extends WearClothes {

    public String action(){
        return null;
    };
}
View Code

4.Hat

/**
 * 帽子
 * 装饰者模式中的ConcreateDecorator,具体的装饰对象。
 * @author huanglg
 *
 */
public class Hat extends Clothes {

    WearClothes wearClothes;
    
    public Hat(WearClothes wearClothes){
        this.wearClothes = wearClothes;
    }
    
    public String action(){
        return "帽子,"+wearClothes.action();
    }

}
View Code

5.Pants

/**
 * 裤子
 * 装饰者模式中的ConcreateDecorator,具体的装饰对象。
 * @author huanglg
 *
 */
public class Pants extends Clothes {

    WearClothes wearClothes;
    
    public Pants(WearClothes wearClothes){
        this.wearClothes = wearClothes;
    }
    
    public String action(){
        return "休闲裤,"+wearClothes.action();
    }
}
View Code

6.Shone

/**
 * 皮鞋
 * @author huanglg
 *
 */
public class Shone extends Clothes {

    WearClothes wearClothes;
    
    public Shone(WearClothes wearClothes){
        this.wearClothes = wearClothes;
    }
    
    public String action(){
        return "皮鞋,"+wearClothes.action();
    }
}
View Code

7.Tshirt

/**
 * T恤
 * 装饰者模式中的ConcreateDecorator,具体的装饰对象。
 * @author huanglg
 *
 */
public class Tshirt extends Clothes {

    WearClothes wearClothes;
    
    public Tshirt(WearClothes wearClothes){
        this.wearClothes = wearClothes;
    }
    
    public String action(){
        return "T恤,"+wearClothes.action();
    }
}
View Code

8.最后的测试类Test

public class Test {

    public static void main(String[] args) {
        WearClothes wearClothes = new Tom();
        Hat hat = new Hat(wearClothes);
        Tshirt tshirt = new Tshirt(hat);
        Pants pants = new Pants(tshirt);
        Shone shone = new Shone(pants);
        String wear = shone.action();
        System.out.println(wear);
    }
}
View Code

 

解析:

WearClothes wearClothes = new Tom();
Hat hat = new Hat(wearClothes);
Tshirt tshirt = new Tshirt(hat);
Pants pants = new Pants(tshirt);
Shone shone = new Shone(pants);
String wear = shone.action();

这段代码中Hat包装了Tom对象,然后通过构造器将Tom对象给了Hat对象中的成员变量WearClothes,

装饰者模式_第1张图片

 

 然后Tshirt又包装了Hat对象,按照测试类中的从上往下的顺序依次包装,最后在运行的时候,最外层的Shone对象执行action()时,里面的wearClothes.action()执行的是

Pants的action方法。

如果还是不太理解,参考https://www.cnblogs.com/yuhanghzsd/p/5364836.html。

你可能感兴趣的:(装饰者模式)