设计模式三之装饰者模式
来源:互联网 发布:xss攻击防御 php 编辑:程序博客网 时间:2024/05/16 15:14
注:本文主要思想来自《HeadFirst 设计模式》
定义:动态地将责任附加到对象上,若要扩展对象,装饰者模式提供了比继承更弹性的替代方案
->遵循开放-关闭原则(对拓展开放,对修改关闭 即不能修改原先的代码进行拓展)
我这里举咸蛋超人的例子说明:
怪物降临,咸蛋超人从天而降。然而此时的咸蛋超人是刚进新手村的,所以战斗力只有5
public interface Superman {String Weapon(); //武器int FightCapacity();//战斗力}咸蛋超人类,继承了Superman接口
public class Ultraman implements Superman{String weapon = "裤衩"; //刚进新手村,身上只有一件绑定衣服(裤衩)int fight = 5; //战斗力只有五的public String Weapon(){return weapon;}public int FightCapacity(){return fight;}}在主类中运行
public class Test {public static void main(String[] args) {Superman man = new Ultraman();man = new Stealth(man);man = new LaserGun(man);System.out.println("现在装备有:"+man.Weapon());System.out.println("现在战斗力有:"+man.FightCapacity());}}
输出为:
现在装备有:裤衩
现在战斗力有:5
于是乎。。。超人刚登场就被怪兽打跑了,但在科学家的思考下决定给超人装备武器,这就是我们的装饰者
科学家在考虑了超人本身是不能拆之后,决定为他添加武器隐形衣和镭射枪
他们定制了一个武器入口,专门用于为超人穿戴武器 这就是 抽象装饰者
public abstract class WeaponDecorator implements Superman{ //定义武器类抽象装饰者//定义武器装饰方法public abstract String Weapon();//定义装备了武器后的增加战斗力方法public abstract int FightCapacity();}有了这个穿戴武器的接口我们就可以穿戴强大的武器(具体装饰者)
具体装饰者 隐形衣类
public class Stealth extends WeaponDecorator{ //武器->隐形衣Superman superman;String weapon = "隐形衣"; //这是件隐形衣int fight = 100; //隐形+100public Stealth(Superman superman){this.superman = superman;}public String Weapon(){return weapon+","+superman.Weapon();}public int FightCapacity(){return fight+superman.FightCapacity();}}具体装饰者 镭射枪类
public class LaserGun extends WeaponDecorator{ //武器->镭射枪Superman superman;String weapon = "镭射枪"; //这是把镭射枪int fight = 50; //隐形+100public LaserGun(Superman superman){this.superman = superman;}public String Weapon(){return weapon+","+superman.Weapon();}public int FightCapacity(){return fight+superman.FightCapacity();}}科学家总于把全部武器生产好了,我们可以为超人装备武器了,在主类中
public class Test {public static void main(String[] args) {Superman man = new Ultraman();man = new Stealth(man);man = new LaserGun(man);System.out.println("现在装备有:"+man.Weapon());System.out.println("现在战斗力有:"+man.FightCapacity());}}输出为:
现在装备有:镭射枪,隐形衣,裤衩
现在战斗力有:155
在科学家的帮忙下,咸蛋超人战斗力剧增,很快就帮怪兽消灭了,地球再次得到了和平-------》》》》》》》》》》》》》》》》》》》》
体会:开放-关闭原则 充分体现了组合-委托的优势,摆脱过度依赖继承,增加程序的弹性
5 0
- 设计模式三之装饰者模式
- 设计模式三之装饰者模式
- 设计模式之装饰者模式 三
- 设计模式之三---装饰者设计模式
- 设计模式之(三、装饰模式Decorator)
- 设计模式之三:装饰器模式
- 设计模式之三:装饰模式(Decorator)
- 设计模式之三装饰模式
- 三、大话设计模式 之 装饰模式
- 设计模式实战应用之三:装饰者模式
- Java设计模式之三--装饰者模式
- 设计模式(三)装饰者模式之java.io
- 设计模式学习(三)之装饰者模式
- 设计模式(三)--装饰者模式(1)
- 设计模式(三)--装饰者模式(2)
- 设计模式(三)装饰者模式
- Java设计模式:三、装饰者模式
- 设计模式(三):装饰者模式
- 极客DIY:用树莓派制作低成本高清监控摄像机
- iOS 基于WebService开发
- linux下设置mysql不区分大小写
- Web 服务编程,REST 与 SOAP
- [Python] 工作日查询脚本
- 设计模式三之装饰者模式
- 支付宝接口使用文档说明 支付宝异步通知(notify_url)与return_url.
- Android常用开源工具(1)-Dagger2入门
- andorid adapteritem 上面的button点击时跳转页面
- HDU1863 并查集与最小生成树
- 逐梦C++补遗篇之一:cout与cerr的区分
- 使用adb shell查看文件
- Mgengto 导入所有产品的图片,按sku命名分类
- (八) shiro + spring + mybatis整合开发