装饰者模式--Java篇

  装饰者模式(Decorator)动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更为灵活。

  1.定义接口,可以动态的给对象添加职责。

1 package com.lujie;
2 
3 public interface SuperPerson {
4     //定义一个接口,可以动态的给对象添加职责
5     public abstract void show() ;
6 }

  2.实现这个接口

 1 package com.lujie;
 2 
 3 public class Person implements SuperPerson{
 4     private String name;
 5     public Person() {
 6         // TODO Auto-generated constructor stub
 7     }
 8     public  Person(String name) {
 9         this.name=name;
10     }
11     //具体对象的操作
12     public void show() {
13         System.out.println("装饰者:"+name);
14     }
15 }

  3.装饰类

 1 package com.lujie;
 2 
 3 public class Finery extends Person{
 4     protected Person component;
 5     //设置component
 6     public void Decorate(Person component) {
 7         this.component=component;
 8     }
 9     //重写show(),实际执行的是component的show()操作
10     public void show() {
11         if(component!=null){
12             component.show();
13         }
14     }
15 
16 }

  4.具体实现的装饰类

1 package com.lujie;
2 
3 public class Shoes extends Finery{
4     //首先执行本类的功能,再运行原Component的show(),相当于对原Component进行了装饰
5     public void show() {
6         System.out.println("皮鞋");
7         super.show();
8     }
9 }
1 package com.lujie;
2 
3 public class Suit extends Finery{
4     //首先执行本类的功能,再运行原Component的show(),相当于对原Component进行了装饰
5     public void show() {
6         System.out.println("西装");
7         super.show();
8     }
9 }
package com.lujie;
//具体服饰类
public class TShirts extends Finery{
    //首先执行本类的功能,再运行原Component的show(),相当于对原Component进行了装饰
    public void show() {
        System.out.println("大体恤");
        super.show();
    }
}
1 package com.lujie;
2 
3 public class WearSneakers extends Finery{
4     public void show() {
5         System.out.println("破球鞋");
6         super.show();
7     }
8 }

  5.测试用例:

 1 package com.lujie;
 2 
 3 public class PersonShowMain {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         Person person=new Person("小明");
 8         System.out.println("第一种装扮:");
 9         WearSneakers wSneakers=new WearSneakers();
10         BigTrouser bigTrouser=new BigTrouser();
11         TShirts tShirts=new TShirts();
12         //装饰过程
13         wSneakers.Decorate(person);
14         bigTrouser.Decorate(wSneakers);
15         tShirts.Decorate(bigTrouser);
16         tShirts.show();
17         //装饰过程二
18         System.out.println("第二种装扮:");
19         Suit suit=new Suit();
20         wSneakers.Decorate(person);
21         bigTrouser.Decorate(wSneakers);
22         suit.Decorate(bigTrouser);
23         suit.show();
24     }
25 
26 }

  6.运行结果:

posted on 2016-04-28 15:21  卢二牛  阅读(251)  评论(0编辑  收藏  举报

导航