黑马程序员技术交流社区

标题: 关于装饰设计模式和继承的区别 [打印本页]

作者: 赵永康    时间: 2012-9-23 13:49
标题: 关于装饰设计模式和继承的区别
看了毕老师总结的装饰设计模式和继承的区别,本人理解了一下,做出如下总结,可能不是很清楚,但是还爱喝大家分享一下
1、装饰设计模式是什么?
   装饰类就是为了增强一个类而存在的。他的出现解决了类的体系臃肿的现象。他一般和被装饰类
   都是属于一个体系。
   reader
-mediareader
  --bufferedmeiareader
datereader
  --buffereddatereader
这就是典型的继承体系。
继承就是为了获得父类的某些方法而存在的。可靠性不是很强
而装饰类一般用了多态的特点,就出现了更加简介的体系。
reader
--mediareader
--datereader
--bufferedreader
其中bufferedreader属于reader的子类  他的具体构造函数如下
class bufferedreader
{
private reader r;
bufferedreader(reader r)
{
  this.r=r;
}
}
在这个类中我们就可以在实例化的时候传入reader类及其子类。并且我们可以继续定义自己特有方法
哈可以调用传入参数的方法。

作者: 尤圣回    时间: 2012-9-23 14:50
装饰模式
概述
    动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
适用性
    1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。

    2.处理那些可以撤消的职责。

    3.当不能采用生成子类的方法进行扩充时。
                         参与者
    1.Component
      定义一个对象接口,可以给这些对象动态地添加职责。

    2.ConcreteComponent
      定义一个对象,可以给这个对象添加一些职责。

    3.Decorator
      维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。

    4.ConcreteDecorator
      向组件添加职责。
类图

例子
Component
public interface Person {

    void eat();
}
ConcreteComponent
public class Man implements Person {

        public void eat() {
                System.out.println("男人在吃");
        }
}
Decorator
public abstract class Decorator implements Person {

    protected Person person;
   
    public void setPerson(Person person) {
        this.person = person;
    }
   
    public void eat() {
        person.eat();
    }
}
ConcreteDecorator
public class ManDecoratorA extends Decorator {

    public void eat() {
        super.eat();
        reEat();
        System.out.println("ManDecoratorA类");
    }

    public void reEat() {
        System.out.println("再吃一顿饭");
    }
}
public class ManDecoratorB extends Decorator {
   
    public void eat() {
        super.eat();
        System.out.println("===============");
        System.out.println("ManDecoratorB类");
    }
}
Test
public class Test {

    public static void main(String[] args) {
        Man man = new Man();
        ManDecoratorA md1 = new ManDecoratorA();
        ManDecoratorB md2 = new ManDecoratorB();
        
        md1.setPerson(man);
        md2.setPerson(md1);
        md2.eat();
    }
}
result
男人在吃
再吃一顿饭
ManDecoratorA类





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