java设计模式学习之装饰模式

时间:2022-11-22 10:47:55

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

优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

缺点:多层装饰比较复杂。

实例:给一个人配置穿衣

1:代码结构图

java设计模式学习之装饰模式

2:创建一个person类(  concretecomponent)

java" id="highlighter_332643">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package decoratormodel;
 
/**
 * 2017-10-9 10:39:09
 * 装饰器设计模式
 * person 类 concretecomponent
 * @author 我不是张英俊
 *
 */
public class person {
 
  public person(){}
  
  private string name;
  public person(string name){
    this.name=name;
  }
  
  public void show(){
    system.out.println("装扮的"+name);
  }
}

3:服饰类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package decoratormodel;
 
/**
 *服饰类(decorator)
 * @author 我不是张英俊
 *
 */
public class finery extends person{
 
  protected person component;
  //打扮
  public void decorate(person component){
    this.component=component;
  }
  
  public void show(){
    if(component!=null){
      component.show();
    }
  }
}

4:具体服饰类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class tshirts extends finery {
  public void show(){
    system.out.println("大t恤");
    super.show();
    }
}
 
public class bigtrouser extends finery {
  public void show(){
    system.out.println("垮裤");
    super.show();
  }
}
 
public class sneakers extends finery {
  public void show(){
    system.out.println("破球鞋");
    super.show();
    }
}
 
public class suit extends finery {
  public void show(){
    system.out.println("西装");
    super.show();
  }
}
 
public class tie extends finery {
  public void show(){
    system.out.println("领带");
    super.show();
  }
}
 
public class leathershoes extends finery {
  public void show(){
    system.out.println("皮鞋");
    super.show();
  }
}

5:测试类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class test {
 
  public static void main(string[] args) {
    person xc=new person("旺财");   
    sneakers pqx=new sneakers();
    bigtrouser kk=new bigtrouser();
    tshirts dtx=new tshirts();
    pqx.decorate(xc);
    kk.decorate(pqx);
    dtx.decorate(kk);
    dtx.show();
  }
 
}

6:控制台

大t恤
垮裤
破球鞋
装扮的旺财

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/hrlizhi/p/7641082.html