设计模式6——装饰模式
来源:互联网 发布:淘宝详情页好做吗 编辑:程序博客网 时间:2024/06/02 05:41
1.什么是装饰模式
装饰( Decorator )模式又叫做包装模式。通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替换方案。
2.装饰模式的结构
举个栗子:
定义一个接口Car,里面有两个抽象类run(),show().
public interface Car { public void show(); public void run();}
如上图,该Car有两个实现,一个是车的基本——会跑的车,另外是车的装饰(抽象类)
public class RunCar implements Car { public void run() { System.out.println("可以跑"); } public void show() { this.run(); }}
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();}
继承修饰类的类就能装饰车了,例如让车会跑又会飞
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() { }}
测试一下
public class MainClass { public static void main(String[] args) { Car car = new RunCar(); car.show(); System.out.println("---------"); Car flycar = new FlyCarDecorator(car); flycar.show(); }}
测试结果:
这时候,又想加一个修饰类去继承CarDecorator,会游泳的类
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() { }}
测试一下,让车又会跑,又会飞,又会跑
public class MainClass { public static void main(String[] args) { Car car = new RunCar(); car.show(); System.out.println("---------"); Car flycar = new FlyCarDecorator(car); flycar.show(); System.out.println("---------"); Car flySwimcar = new SwimCarDecorator(flycar); flySwimcar.show(); }}
测试结果:
3.装饰模式的角色和职责
抽象组件角色(Car): 一个抽象接口,是被装饰类和装饰类的父接口。
具体组件角色(RunCar):为抽象组件的实现类。
抽象装饰角色(CarDecorator):包含一个组件的引用,并定义了与抽象组件一致的接口。
具体装饰角色(FlyCarDecorator):为抽象装饰角色的实现类。负责具体的装饰。
重点:装饰者与被装饰者拥有共同的超类,继承的目的是继承类型,而不是行为
Java中的I/O API就是使用Decorator实现的。多看看代码,就能理解。
阅读全文
0 0
- 设计模式6——装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式—装饰模式
- 设计模式——装饰设计模式
- 设计模式——装饰设计模式
- 设计模式——装饰设计模式
- 【设计模式】——Decorator装饰模式
- 每日设计模式——装饰模式
- 设计模式——装饰者模式
- 设计模式——装饰模式
- 设计模式——装饰模式
- java设计模式——装饰模式
- 设计模式——装饰者模式
- 大话设计模式——装饰模式
- 设计模式——装饰模式
- django channels websocket 聊天室
- SqlServer中对应的有外键的主表数据,无法truncate表的处理
- 对oracle中分组函数的一点感悟
- POJ-1284 Primitive Roots 欧拉函数
- javascript闭包传参和事件的循环绑定示例探讨
- 设计模式6——装饰模式
- 白盒测试方法
- LDAP服务器的概念和原理简单介绍
- Python中__str__和__repr__
- [P1378]油滴扩展
- Markdown的简单用法
- 阿里云助力网络安全社区MMBEST,书写云上新面貌
- canvas里面刷新界面,有时候图片能出来 有时候不能
- 欢迎使用CSDN-markdown编辑器