炒冷饭系列:设计模式 装饰模式

来源:互联网 发布:数据库监控 编辑:程序博客网 时间:2024/06/03 01:52

炒冷饭系列:设计模式 装饰模式

摘要: 原创出处: http://www.cnblogs.com/Alandre/ 泥沙砖瓦浆木匠 希望转载,保留摘要,谢谢!

钢琴弹得好是艺术,文章写的好也是艺术。

一、什么是装饰模式抽象工厂模式

二、装饰模式的结构 角色和职责

三、装饰模式实现

一、什么是抽象工厂模式

装饰( Decorator )模式又叫做包装模式。通 过一种对客户端透明的方式来扩展对象的功能, 是继承关系的一个替换方案。

二、装饰模式的结构 角色和职责

以下是对此图的见解,不服别喷403A29~1[4]。Component是实体接口 或者 抽象类。左边的ConcreteComponent是其实现(功能)。Decorator装饰,所谓的装饰抽象类就是把接口类实现,然后加上DoSomething的模块。

然后下面就是各个对具体装饰的实现,如果需要多功能结合 不是相互结合,而是通过父类抽象结合对象达到目的。具体可以参考下面案例的实现图解。

                             image

抽象组件角色: 一个抽象接口,是被装饰类和 装饰类的父接口。

具体组件角色:为抽象组件的实现类。

抽象装饰角色:包含一个组件的引用,并定义了 与抽象组件一致的接口。

具体装饰角色:为抽象装饰角色的实现类。负责 具体的装饰。

三、装饰模式实现

局部类图:

image

具体实现:

Car

复制代码
public interface Car {        public void show();        public void run();}
复制代码
RunCar
复制代码
public class RunCar implements Car {    public void run() {        System.out.println("可以跑");    }    public void show() {        this.run();    }}
复制代码

CarDecorator

复制代码
public abstract class CarDecorator implements Car{    private Car car;        public Car getCar() {        return car;    }    public void setCar(Car car) {        this.car = car;    }    public CarDecorator(Car car) {        this.car = car;    }        public abstract void show();}
复制代码

 

上面相当于搭了好架子,后面需要具体实现了。

FlyCarDecorator

复制代码
public class FlyCarDecorator extends CarDecorator{    public FlyCarDecorator(Car car) {        super(car);    }    public void show() {        this.getCar().show();        this.fly();    }        public void fly() {        System.out.println("可以飞");    }    public void run() {            }}
复制代码

SwimCarDecorator

复制代码
public class SwimCarDecorator extends CarDecorator {    public SwimCarDecorator(Car car) {        super(car);    }    public void show() {        this.getCar().show();        this.swim();    }        public void swim() {        System.out.println("可以游");    }    public void run() {            }}
复制代码

 

然后测试代码

MainClass

复制代码
public class MainClass {    public static void main(String[] args) {        Car car = new RunCar();                car.show();        System.out.println("---------");                Car swimcar = new SwimCarDecorator(car);        swimcar.show();        System.out.println("---------");                Car flySwimCar = new FlyCarDecorator(swimcar);        flySwimCar.show();    }}
复制代码

运行可以得到以下结果:

复制代码
可以跑---------可以跑可以游---------可以跑可以游可以飞
复制代码

四、感谢知识来源和小结

一、什么是装饰模式抽象工厂模式

二、装饰模式的结构 角色和职责

三、装饰模式实现

来自:java设计模式

如以上文章或链接对你有帮助的话,别忘了在文章按钮或到页面右下角点击 “赞一个” 按钮哦。你也可以点击页面右边“分享”悬浮按钮哦,让更多的人阅读这篇文章。

书法是心领神会的艺术

鄙人书法欣赏:

               QQ Photo20140810092646

1 0