二. 角色Decorator(装饰模式):动态地给一个对象添加一些额外的职责。就扩展功能而言, 它比生成子类方式更为灵活。
三. 实现抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。装饰(Decorator)角色:持有一个构件(Component)角色对象的实例,并定义一个与抽象构件接口一致的接口。具体装饰(ConcreteDecorator)角色:负责给构件对象贴上附加的责任。
一个人往往有许多身份,比如一个男人,他是一个人,同时也可能是父亲,丈夫,也可能是程序员,这是父亲、丈夫和程序员就是具体装饰角色,人则是抽象构件角色,男人则为具体构件角色。Test.javapublic class Test {public static void main(String[] args) {Decorator fatherDecorator = new FatherDecorator();Decorator husbandDecorator = new HusbandDecorator();Decorator programmerDecorator = new Programmer();Human like = new Male();fatherDecorator.setHuman(like);husbandDecorator.setHuman(fatherDecorator);programmerDecorator.setHuman(husbandDecorator);programmerDecorator.work();}}测试类,定义一个Human,分别给他装饰丈夫,父亲和程序员。Human.javapublic interface Human {public void work();}人类,为抽象构件角色。Male.javapublic class Male implements Human {@Overridepublic void work() {System.out.println("好好活着");}}男人类,继承与人类,是具体构件角色。Decorator.javapublic class Decorator implements Human {private Human human;public Human getHuman() {return human;}public Decorator setHuman(Human human) {this.human = human;return this;}public Decorator(){}public Decorator(Human human) {super();this.human = human;}@Overridepublic void work() {this.human.work();}}装饰角色。其中有一个抽象构件的对象。FatherDecorator.javapublic class FatherDecorator extends Decorator {@Overridepublic void work(){System.out.println("保护孩子");super.getHuman().work();}}父亲装饰类,具体装饰类。HusbandDecorator.javapublic class HusbandDecorator extends Decorator {@Overridepublic void work(){System.out.println("保护妻子");super.getHuman().work();}}丈夫装饰类,具体装饰类。Programmer.javapublic class Programmer extends Decorator {@Overridepublic void work(){System.out.println("写好程序");super.getHuman().work();}}程序员类,具体装饰类。
联系客服