码迷,mamicode.com
首页 > 其他好文 > 详细

装饰者模式

时间:2016-09-26 23:13:07      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:

 * 通过使用修饰模式,可以在运行时扩充一个类的功能。

 * 原理是:增加一个修饰类包裹原来的类,包裹的方式一般是通过在将原来的对象作为修饰类的构造函数的参数。

 * 装饰类实现新的功能,而在不需要用到新功能的地方,它可以直接调用原来的类中的方法。

 * 修饰类必须和原来的类有相同的接口。

 * 修饰模式是类继承的另外一种选择。类继承在编译时候增加行为,而装饰模式是在运行时增加行为。

 * 当某个类具有多种可组合叠加的行为或属性时,装饰者模式可以通过动态增加装饰类,以避免排列组合,减少需要类的数量。

 

共同的接口

1 public interface ITree {
2      void show();  
3 }

 

原本的类

1 public class Tree implements ITree {
2 
3     @Override
4     public void show() {
5         System.out.println("I am a tree");  
6     }
7 
8 }

 

装饰类1

 1 public class DecoratorApple implements ITree {
 2 
 3     private ITree tree;
 4 
 5     public DecoratorApple(ITree tree) {
 6         super();
 7         this.tree = tree;
 8     }
 9 
10     public void show() {
11         tree.show();
12         System.out.println(" with apple");
13     }
14 
15 }

 

装饰类2

 1 public class DecoratorGift implements ITree {
 2 
 3     private ITree tree;
 4 
 5     public DecoratorGift(ITree tree) {
 6         super();
 7         this.tree = tree;
 8     }
 9 
10     public void show() {
11         tree.show();
12         System.out.println("with gift");
13     }
14 }

 

装饰类3

 1 public class DecoratorSnow implements ITree {
 2 
 3     private ITree tree;
 4 
 5     public DecoratorSnow(ITree tree) {
 6         super();
 7         this.tree = tree;
 8     }
 9 
10     public void show() {
11         tree.show();
12         System.out.println("with snow");
13     }
14 }

 

使用

 1 public class TestDecorator {
 2 
 3     public static void main(String[] args) {
 4         
 5         //普通的树
 6         ITree tree = new Tree();
 7 
 8         // 装饰成一个苹果树
 9         ITree appleTree = new DecoratorApple(tree);
10         appleTree.show();
11         
12         // 进一步装饰雪
13         ITree snowTree = new DecoratorApple(new DecoratorSnow(appleTree));
14         snowTree.show();
15         
16         // 装饰成一个圣诞树
17         ITree christmasTree = new DecoratorGift(snowTree);
18         christmasTree.show();    
19     }
20 }

 

 

 

 

 

 

 

 

装饰者模式

标签:

原文地址:http://www.cnblogs.com/luangeng/p/5911039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!