Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1782464
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Java

2017-02-14 12:07:30

This Pattern is used to extend the functionality of an object dynamically without having to change 
the original class source or using inheritance. This is accomplished by creating an object wrapper
referred to as Decorator around the actual object. 

Component Interface: The interface or abstract class defining the methods that will be implemented.
Component Implementation: The basic implementation of the component interface 
Decorator: Decorator class implements the component interface and it has a HAS-A relationship 
with the component interface. The component variable should be accessible to the child decorator 
classes.
Concrete Decorator: Extending the base decorator functionality and modifying the component behavior according. 

Usage in java: 
used a lot in Java IO classes, such as FileReader, BufferedReader. 

概念复杂,代码很简单.

点击(此处)折叠或打开

  1. package decorator;

  2. interface Icecream{
  3.     public String makeIceCream();
  4. }

  5. class SimpleIceCream implements Icecream{
  6.     @Override
  7.     public String makeIceCream(){
  8.         return "Base - IceCream";
  9.     }
  10. }

  11. class IceCreamDecorator implements Icecream{
  12.     protected Icecream specialIcecream;

  13.     public IceCreamDecorator(Icecream specialIcecream){
  14.         this.specialIcecream = specialIcecream;
  15.     }

  16.     @Override
  17.     public String makeIceCream(){
  18.         return specialIcecream.makeIceCream();
  19.     }
  20. }


  21. //Concrete Decorator
  22. class NuttyDecorator extends IceCreamDecorator{

  23.     public NuttyDecorator(Icecream specialIcecream){
  24.         super(specialIcecream);
  25.     }

  26.     @Override
  27.     public String makeIceCream(){
  28.         return specialIcecream.makeIceCream()+addNuts();
  29.     }

  30.     private String addNuts(){
  31.         return " + Cruncky Nuts";
  32.     }
  33. }


  34. //Concrete Decorator
  35. class HoneyDecorator extends IceCreamDecorator{
  36.     public HoneyDecorator(Icecream IceCreamDecorator){
  37.         super(IceCreamDecorator);
  38.     }

  39.     @Override
  40.     public String makeIceCream(){
  41.         return specialIcecream.makeIceCream()+addHoney();
  42.     }

  43.     private String addHoney(){
  44.         return " + Sweet Honey";
  45.     }
  46. }

  47. public class DecoratorPatternDemo {
  48.     public static void main(String[] args){
  49.         Icecream ic = new HoneyDecorator(new NuttyDecorator(new SimpleIceCream()));
  50.         System.out.println(ic.makeIceCream());
  51.     }
  52. }


阅读(561) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~