装饰模式(结构型)
来源:互联网 发布:麦迪职业生涯数据统计 编辑:程序博客网 时间:2024/06/07 04:49
定义:动态地给一个对象添加一些额外的职责,是继承关系的一个替代方案
结构:
- 抽象组件:被装饰的原始对象抽象,接口或者抽象类
- 具体组件:组件的具体实现,是装饰的具体对象
- 抽象装饰者:装饰组件对象,内部有一个指向组件对象的引用,通常为抽象类
- 具体装饰着:装饰着具体实现
适用场景:需要透明且动态扩展类的功能时
UML类图:
下面就是装饰模式的代码实现,以人穿衣服为例子:
Component:
public abstract class Person { abstract void dress();}public class Male extends Person{ String name; public Male(String name) { this.name = name; } @Override public void dress() { System.out.println(name+"\r穿内衣内裤"); }}
Decorator:
public abstract class PersonCloth extends Person{ Person person; public PersonCloth(Person person){ this.person = person; } public void dress(){ person.dress(); }}public class CheapCloth extends PersonCloth{ public CheapCloth(Person person) { super(person); } private void dressShirt(){ System.out.println("穿地摊货短袖"); } private void dressTrousers(){ System.out.println("穿地摊货运动裤"); } private void dressShoes(){ System.out.println("穿地摊货球鞋"); } public void dress(){ super.dress(); dressShirt(); dressTrousers(); dressShoes(); }}public class ExpensiveCloth extends PersonCloth{ public ExpensiveCloth(Person person) { super(person); } private void dressShirt(){ System.out.println("穿nike短袖"); } private void dressTrousers(){ System.out.println("穿nike运动裤"); } private void dressShoes(){ System.out.println("穿nike球鞋"); } private void dressCap(){ System.out.println("再带一个帽子"); } public void dress(){ super.dress(); dressShirt(); dressTrousers(); dressShoes(); dressCap(); }}
Test:
public class Test { public static void main(String[] args){ Person p = new Male("李雷"); PersonCloth cCloth = new CheapCloth(p); cCloth.dress();// PersonCloth eCloth = new ExpensiveCloth(p);// eCloth.dress(); }}
总结:参考https://www.kancloud.cn/digest/xing-designpattern/143730
0 0
- 装饰模式(结构型)
- 结构型模式-----装饰模式(decorator)
- 装饰模式(结构型模式)
- (结构型模式二)装饰模式
- Decorator模式(装饰模式 结构型)
- 结构型模式-装饰
- 结构型模式-装饰模式
- 结构型模式-装饰模式
- Decorator 装饰(结构型模式)
- 结构型模式:Decorator(装饰)
- 装饰器模式Decorator(结构型)
- Decorator装饰设计模式(结构型)
- 结构型模式之装饰(Decorator)
- 装饰模式Decorator(结构型)
- (8)设计模式之装饰模式(结构型模式)
- Decorator装饰(结构型模式)
- 结构型模式-装饰模型
- 【结构型模式】decorator(装饰)
- SSM 配置
- 【问题 解决】mxnet训练mnist数据集的Train_accuracy很小
- 初探MeidaPlayer底层实现(一)
- 个人常用sql语句记录
- SDL库的学习笔记之四—事件处理
- 装饰模式(结构型)
- springMVC使用ehcache实现简单的单点登录
- 解决方法:android 6.0(api 23) SDK,不再提供org.apache.http.*(只保留几个类)
- java web —— JSP指令与动作元素
- LeetCode 481. Magical String
- Oracle11g安装注意事项
- 游戏开发之在UE4中编写C++代码控制角色
- 【数据库——锁】
- 组播IGMP的测试小结