装饰器模式

来源:互联网 发布:程序员怎么在北京生活 编辑:程序博客网 时间:2024/06/15 09:06

今天学习了装饰器模式,总结一下:

百度百科对装饰器模式的解释:在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

其要点是
1. 不改变原类文件
2. 尽量少用继承
3. 动态扩展

装饰模式的特点
(1) 装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。
(2) 装饰对象包含一个真实对象的引用(reference)
(3) 装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。
(4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

直接看代码

package decorator;//待装饰的接口,但不是必须的public interface Car {    public void run();}
package decorator;//待装饰对象public class BenC implements Car{    @Override    public void run() {        System.out.println("奔驰跑");    }}
package decorator;//装饰器父类,定义装饰器的目标,并且对原始类(Car)进行基本的装饰public abstract class Decorator implements Car{  //和装饰对象具有相同的接口    protected Car car; //对一个真实对象的引用    public Decorator(Car car) {        super();        this.car = car;    }    public void run(){        car.run();    }}
package decorator;//装饰者A,给奔驰喷个绿色public class DecoratorA extends Decorator{    public DecoratorA(Car car) {        super(car);    }    public void color(){        System.out.println("喷绿色");    }    public void run(){        System.out.println("在A中增加一个装饰");        super.run();        System.out.println("A装饰结束");    }}
package decorator;//装饰者B,给奔驰加个保险杠public class DecoratorB extends Decorator{    public DecoratorB(Car car) {        super(car);    }    public void bumper(){        System.out.println("加保险扛");    }    @Override    public void run() {        System.out.println("在B中增加一个装饰");        super.run();        System.out.println("B装饰结束");    }}
package decorator;public class Main {    public static void main(String[] args) {        System.out.println("-----------未加装饰前begin---------------");        BenC bc = new BenC();        bc.run();        System.out.println("-----------未加装饰前end---------------");        System.out.println();        System.out.println("-----------A装饰者begin---------------");        DecoratorA da = new DecoratorA(bc);        da.run();        da.color();        System.out.println("-----------A装饰者end---------------");        System.out.println();        System.out.println("-----------B装饰者begin---------------");        DecoratorB db = new DecoratorB(bc);        db.run();        db.bumper();        System.out.println("-----------B装饰者end---------------");        System.out.println();        System.out.println("-----------A装饰者后B在装饰begin---------------");        DecoratorB db2 = new DecoratorB(da);        db2.run();        db2.bumper();        System.out.println("-----------A装饰者后B在装饰end---------------");    }}

测试结果
这里写图片描述

装饰器模式在Java中最经典的应用就是I/O操作。

总结:设计模式的学习需要循环渐进,一时想不明白的地方可能会在以后慢慢的理解中顿悟;
学习别的东西也是如此,只要有心学习,总有一天都会理解其中的奥妙。

0 0
原创粉丝点击