装饰模式
来源:互联网 发布:阿里云主机多少钱 编辑:程序博客网 时间:2024/05/19 02:45
百度百科
装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。
在装饰模式中的各个角色有:
- 抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
- 具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
- 装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
- 具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。
本例子以游戏战舰世界为例子。
原始接口船(抽象构件(Component)角色)
public interface Ship { public void move();}
战舰(具体构件(Concrete Component)角色)
public class WarShip implements Ship{ @Override public void move() { System.out.println("移动"); }}
给战舰添加各种功能的工厂(装饰(Decorator)角色)
public class Factory implements Ship{ private Ship ship; //既然要给船添加功能,必须要开来一条船 public Factory(Ship ship) { this.ship = ship; } @Override public void move() { ship.move(); }}
添加信号旗(具体装饰(Concrete Decorator)角色)
public class Weft extends Factory{ @Override public void move() { super.move(); fire(); } public void fire() { System.out.println("增加炮火"); } public Weft(Ship ship) { super(ship); }}
添加涂装(具体装饰(Concrete Decorator)角色)
public class Painting extends Factory{ @Override public void move() { super.move(); painting(); } public void painting() { System.out.println("增加隐蔽性 "); } public Painting(Ship ship) { super(ship); }}
客户端方法
public class Main { public static void main(String[] args) { Ship ship = new WarShip(); Ship war = new Painting(new Weft(ship)); war.move(); }}
阅读全文
0 0
- 装饰模式-撤销装饰
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- TensorFolw学习笔记-TFRecord
- Leetcode个人题解712
- 数据可视化的未来趋势分析
- ArcGIS的swm二进制文件处理成为矩阵形式的文本文件
- MySQL 悲观锁和乐观锁和共享锁
- 装饰模式
- 多线程并发系统-----讲解
- Android中评分条AppCompatRatingBar
- Ajax原理与封装
- 数据结构
- Android Architecture Components(1)
- SpringBoot非官方教程 | 第十七篇:上传文件
- symbol(s) not found for architecture arm64
- 索引失效原因