黑马程序员技术交流社区

标题: 关于毕老师说的BufferedReader中readLine方法采用装饰设计模式... [打印本页]

作者: 冯华亮    时间: 2012-8-4 02:17
标题: 关于毕老师说的BufferedReader中readLine方法采用装饰设计模式...
昨天看完毕老师的IO流章视频教程,颇有感触,老师在讲到BufferedReader中readerLine方法时说到,其本质上是read方法的一个增强,采用是的Dercorator设计模式,额外的为类添加职责行为,该设计模式利用多态思想,实现了高内聚,低耦合,提高了程序的复用性和健壮性。以后诸多常用类均有使用 ,我就试着写了比较简单java版Decorator设计模式样本,分享一下 。好了 废话不多说,上代码!
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */

  5. package javaapplication10;
  6. /*
  7. *
  8. * @author Any
  9. */
  10. public class Main {

  11.     /**
  12.      * @param args the command line arguments
  13.      */
  14.     public static void main(String[] args)
  15.     {
  16.         // TODO code application logic here
  17.         Component _com=new ConcreteComponent();
  18.         Decorator _dec=new ConcreteDecorator(_com);
  19.         _dec.Operation();
  20.         

  21.     }

  22. }
  23. //定义一个抽象基类,实现多态
  24. abstract class Component {
  25.     protected Component(){}
  26.     public abstract  void Operation();


  27. }
  28. class ConcreteComponent extends Component{
  29.     public ConcreteComponent(){};
  30.     public void Operation(){
  31.         System.out.println("ConcreteComponent::Operation");
  32.     }

  33. }
  34. class Decorator extends Component{
  35.    protected Component _com;
  36.     public Decorator(){};
  37.     public Decorator(Component _com){
  38.         this._com=_com;
  39.     }
  40.     public void Operation(){
  41.         System.out.println("Decorator::Operation");

  42.     }

  43. }
  44. class ConcreteDecorator extends Decorator{
  45.    public ConcreteDecorator(Component _com){
  46.        super(_com);
  47.           }
  48.     //Override
  49. <font color="#ff0000">//将增强职责部分添加此处,以便于实现增强功能</font>
  50.        public void Operation(){
  51.            _com.Operation();
  52.            this.AddBehavior();

  53.        }
  54. <font color="#ff0000">//这就是要增强职责行为部分,可自行添加想要实现的职责行为</font>
  55.        public void AddBehavior(){
  56.            System.out.println("ConcreteDecorator::AddBehavior");
  57.        }


  58. }
复制代码

作者: 郑小杰    时间: 2012-8-4 12:42
很给力啊,加油




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2