好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java设计模式笔记之装饰模式

一、装饰模式的定义

装饰模式是一种比较常见的模式,其定义如下:attach additional responsibilities to an object dynamically keeping the same interface.decorators provide a flexible alternative to subclassing for extending functionality.(动态地给一个对象添加额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活)

装饰模式的通用类图如图:

component抽象构件:component是一个接口或者是抽象类,就是定义我们最核心的对象,也就是最原始的对象

concretecomponent具体构件:concretecomponent是最核心、最原始、最基本的接口或抽象类的实现,你要装饰的就是它

decorator装饰角色:一般一个抽象类,做什么用呢?实现接口或抽象方法,这里面不一定有抽象的方法,在它的属性里必然有一个private变量指向component抽象构件

具体装饰角色:concretedecoratora和concretedecoratorb是两个具体的装饰类,你要把你最核心的、最原始的、最基本的东西装饰成其他东西

抽象构件代码:

?

1

2

3

4

public abstract class component {

   //抽象的方法

   public abstract void operate();

}

具体构件代码:

?

1

2

3

4

5

6

public class concretecomponent extends component {

   @override

   public void operate() {

     system.out.println( "do somthing" );

   }

}

抽象装饰者:

?

1

2

3

4

5

6

7

8

9

10

11

12

public abstract class decorator extends component {

   private component component = null ;

 

   public decorator(component component) {

     this 测试数据ponent = component;

   }

 

   @override

   public void operate() {

     this 测试数据ponent.operate();

   }

}

具体装饰类:

?

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

public class concretedecorator1 extends decorator {

   public concretedecorator1(component component) {

     super (component);

   }

 

   private void method1() {

     system.out.println( "method1 修饰" );

   }

 

   @override

   public void operate() {

     this .method1();

     super .operate();

   }

}

public class concretedecorator2 extends decorator {

   public concretedecorator2(component component) {

     super (component);

   }

 

   private void method2() {

     system.out.println( "method2 修饰" );

   }

 

   @override

   public void operate() {

     this .method2();

     super .operate();

   }

}

场景类:

?

1

2

3

4

5

6

7

8

9

10

11

public class client {

   public static void main(string args[]) {

     component component = new concretecomponent();

     //第一次修饰

     component = new concretedecorator1(component);

     //第二次修饰

     component = new concretedecorator2(component);

     //修饰后运行

     component.operate();

   }

}

二、装饰的优缺点和使用场景

优点:

装饰类与被装饰类可以独立发展,而不会相互耦合。换句话说,component类无需知道decorator类,decorator类是从外部扩展component类的功能,而decorator也不用知道具体的构件

装饰模式是继承关系的一个替代方案。我们看装饰类decorator,不管装饰多少层,返回的还是component,实现的还是is-a的关系

装饰模式可以动态地扩展一个实现类的功能

缺点:

对于装饰模式记住一点就够了:多层的装饰是比较复杂的,就像剥洋葱,剥到了最后才发现是最里层的装饰出现了问题,因此尽量减少装饰类的数量,以便降低系统的复杂度。

使用场景:

需要扩展一个累的功能,或者给一个类增加附加功能
需要动态地给一个对象增加功能,这些功能可以再动态的撤销
需要为一批兄弟累进行改装或假装功能,当然首选装饰模式

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

查看更多关于java设计模式笔记之装饰模式的详细内容...

  阅读:15次