【结构型模式】《大话设计模式》——读后感 (3)穿什么有这么重要?——装饰模式之理解实例(2)

UML代码结构图:

 

 

Clothes接口:

package com.sjmx.decorator.thrid;

public interface Clothes {
    
    public void addClothes();
    
}

最简单的功能:

package com.sjmx.decorator.thrid;

public class Person implements Clothes{
    
    @Override
    public void addClothes() {
         System.out.println("java开始起床,先穿内裤");
    }
    
    public void ak() {
         System.out.println("1");
    }
}

装饰抽象类 Decorator模拟:

package com.sjmx.decorator.thrid;

public abstract class DecClothes implements Clothes {
    
    private Clothes clo ;    
    
    public DecClothes(Clothes c) {
        this.clo = c;
    }
    
    @Override
    public void addClothes() {
        if(clo != null){
            clo.addClothes();
        }
    }

}

Decorator的实现A:

package com.sjmx.decorator.thrid;

public class PerClothA extends DecClothes {

    public PerClothA(Clothes c) {
        super(c);
    }
    
    @Override
    public void addClothes() {
         super.addClothes();
         System.out.println("A开始穿裤子");
    }
}

Decorator的实现A:

package com.sjmx.decorator.thrid;

public class PerClothB  extends DecClothes {

    public PerClothB(Clothes c) {
        super(c);
    }
    
    @Override
    public void addClothes() {
         super.addClothes();
         System.out.println("A开始穿外套");
    }
}

客户端代码:

package com.sjmx.decorator.thrid;

public class Client {
   
    public static void main(String[] args) {
        
        Person p = new Person();
        p.addClothes();
        System.out.println("-----------------");
        
        PerClothA a = new PerClothA(p);
        a.addClothes();
        System.out.println("-----------------");
        
        PerClothB b = new PerClothB(p);
        b.addClothes();
        System.out.println("-----------------");
        
        PerClothB c = new PerClothB(a);
        c.addClothes();
        System.out.println("-----------------");
        
        PerClothA d = new PerClothA(b);
        d.addClothes();
    }
}

运行结构:

 

总结:

1、从装饰模式的定义我们知道,装饰模式是动态的个对象添加额外的职责(功能)的。

2、为什么DecClothes抽象类要去实现Clothes接口,而后PerClothA、PerClothB再去继承DecClothes,而不是去直接实现接口?

  答:a、抽象类可以让拥有的方法有一些默认的逻辑实现,而接口绝对不能有方法实现,这是DecClothes存在的原因之一;

              b、 DecClothes抽象类实现了Clothes接口的addClothes()方法,同时有增持了Clothes类型的变量,这样的话,就可以确保无论DecClothes类有多少实现类,这些实现类同时也都是Clothes的实现类,这是多态决定的,这是原因二;

      c、PerClothA、PerClothB、C、D、E、F、G等等,无论有多少个实现类,也无论是A包装B,还是B包装A,都可以实现,因为PerClothA、PerClothB、C、D、E、F、G都是Clothes的实现类,通过多态理解他们都是Clothes,而Clothes只是DecClothes的一个变量,而PerClothA、PerClothB、C、D、E、F、G又是DecClothes的实现类,那就保证PerClothA既是Clothes类型,又可以包含其他具体实现了DecClothes抽象类的子类,这是最重要的原因。(可能意会比言传要好一些)

 

posted @ 2017-06-20 21:50  街头小瘪三  阅读(219)  评论(0编辑  收藏  举报