设计模式之装饰模式

装饰模式——Decorator Pattern

装饰模式用于将核心功能与锦上添花的功能分开(锦上添花的功能是可加也可以不加的那种)

一般情况只使用核心功能的代码就行,当需要特殊功能时可以有选择地,按照一定顺序使用装饰功能包装对象。

一般组成:

  •   对象接口 Component (抽象类)
  •   具体对象 ConcreteComponent(继承对象接口)
  •   装饰抽象类 Decorator(继承对象接口) 
  •   具体装饰对象  ConcreteDecorator(继承装饰抽象类,实现具体的装饰功能)

简明的组成:

  •   具体对象(实现核心功能的对象)
  •   装饰抽象类(继承具体对象)
  •   具体装饰对象(继承装饰抽象类,实现具体的装饰功能)

以人穿衣服为例

具体对象 Person

 1 public class Person {
 2     public  Person(){}
 3     private String name;
 4     public Person(String name)
 5     {
 6         this.name=name;
 7     }
 8     public void Show()
 9     {
10         System.out.println("装扮的会吃喝拉撒的"+name);//核心功能
11     }
12 }

装饰类 Decorator

 1 public class Decorator extends Person  {
 2     protected Person component;
 3     public void Decorate(Person component)
 4     {
 5         this.component=component;
 6     }
 7 
 8     @Override
 9     public void Show() {
10         if(component!=null)
11         {
12             component.Show();
13         }
14     }
15 }

具体装饰对象 裤子

1 public class Pants extends Decorator {
2     @Override
3     public void Show() {
4         System.out.print("裤子  ");
5         super.Show();
6     }
7 }

主函数

 1 public class Client {
 2     public static void main(String[] args) {
 3         Person person=new Person("lancelee");
 4         Pants pants=new Pants();
 5         Shoe shoe=new Shoe();
 6         Tshirts tshirts=new Tshirts();
 7 
 8         pants.Decorate(person);
 9         shoe.Decorate(pants);
10         tshirts.Decorate(shoe);
11 
12         tshirts.Show();
13     }
14 }

  其中逻辑理解如下:

    由于Pants继承了Decorator ,所以继承了Decorator中的构造方法与其重载的Show方法。

    Pants构造函数传入了person对象,component不为空,所以Decorator的Show方法调用了Person中的Show方法。

    由于Pants继承了Decorator 所以也要重载Decorator的Show方法——先加上Pants独有的穿上裤子这个装饰方法,再调用Decorator中的Show方法。

    所以现在的输出就是 裤子 装扮的会吃喝拉撒的lancelee。

    然后再用其他的装饰类装饰裤子,依次进行装饰,就可以达到目的。

相关代码:https://github.com/lancelee98/DesignPattern/tree/master/src/DecoratorPattern

    

    

原文地址:https://www.cnblogs.com/lancelee98/p/10274915.html