@BertLee
2017-08-10T08:35:09.000000Z
字数 1682
阅读 1040
装饰者模式能够在不使用创造子类的情况下,将对象的功能加以扩展,如果要撤销功能的话,也比较方便。
在装饰者模式中,含有的角色:
- 抽象构件角色:接口或者抽象类,给出了需要装饰的接口。
- 具体构件角色:类,包含了被装饰者所有的功能。
- 装饰角色:类,持有抽象构建角色的委托实例,并实现了抽象构件角色的接口。
- 具体装饰角色:类,继承装饰角色,对于需要装饰的方法进行增强。
装饰者的结构如下图:

套路:
1. 创建1个抽象装饰类
2. 创建委托实例,由客户端初始化
3. 实现抽象构件接口,通过委托实例,与原来接口保持一致
4. 创建具体装饰类,继承抽象装饰类,对要增强的功能增强
/*** 抽象构件角色,士兵战斗接口*/public interface Fightable {//穿盔甲public void wearArmour();//佩剑public void carrySword();}
/*** 具体构件角色,士兵*/public class Soldier implements Fightable{public void wearArmour() {System.out.println("身穿连衣裙");}public void carrySword() {System.out.println("佩戴铅笔刀");}}
/*** 抽象装饰角色,士兵装饰者*/public class SoldierDecorator implements Fightable{private Fightable fightablePerson;public SoldierDecorator(Fightable fightablePerson){this.fightablePerson = fightablePerson;}//原封不动public void wearArmour() {fightablePerson.wearArmour();}//原封不动public void carrySword() {fightablePerson.carrySword();}}
/*** 具体装饰者,士兵包裹类*/public class SoldierWrapper extends SoldierDecorator {public SoldierWrapper(Fightable fightablePerson) {super(fightablePerson);}@Overridepublic void wearArmour() {super.wearArmour();System.out.println("增强后---------");System.out.println("穿戴铠甲");}@Overridepublic void carrySword() {super.carrySword();System.out.println("增强后-----------");System.out.println("佩戴七星宝刀");}}
/*** 测试装饰者模式*/public class DecoratorTest {@Testpublic void testDecorator(){SoldierWrapper soldierWrapper = new SoldierWrapper(new Soldier());soldierWrapper.carrySword();System.out.println("分割线------------");soldierWrapper.wearArmour();}}
撰写本文考了不少博文,在此一并谢过。
《JAVA与模式》之装饰模式转载时,请注明出处,这是人格的一种体现。
https://www.zybuluo.com/BertLee/note/845814- 能力有限,如有纰漏,请在评论区指出,老朽虽一把年纪,必当感激涕零,泪如雨下。若有满嘴喷粪撕逼者,一律拉黑、举报。