读书人

装点器模式

发布时间: 2012-08-10 12:19:33 作者: rapoo

装饰器模式

装饰器模式:即客户端先调用的接口A,现在客户端需要在调用接口A的时候,期望A有更多的功能。

?

具体代码如下:

?

package com.mkf.pattern;public interface InterfaceOne {public void operation();}package com.mkf.pattern.impl;import com.mkf.pattern.InterfaceOne;public class Source implements InterfaceOne {@Overridepublic void operation() {System.out.println("源被调用:" + Source.class.getName());}}package com.mkf.pattern.impl;import com.mkf.pattern.InterfaceOne;public class DecoratorOne implements InterfaceOne {private InterfaceOne io;public DecoratorOne(InterfaceOne io) {super();this.io = io;}@Overridepublic void operation() {System.out.println("DecoratorOne 增强功能前");io.operation();System.out.println("DecoratorOne 增强功能后");}}package com.mkf.pattern.impl;import com.mkf.pattern.InterfaceOne;public class DecoratorTwo implements InterfaceOne {private InterfaceOne io;public DecoratorTwo(InterfaceOne io) {super();this.io = io;}@Overridepublic void operation() {System.out.println("DecoratorTwo 增强功能前");io.operation();System.out.println("DecoratorTwo 增强功能后");}}package com.mkf.pattern.impl;import com.mkf.pattern.InterfaceOne;public class DecoratorThree implements InterfaceOne {private InterfaceOne io;public DecoratorThree(InterfaceOne io) {super();this.io = io;}@Overridepublic void operation() {System.out.println("DecoratorThree 增强功能前");io.operation();System.out.println("DecoratorThree 增强功能后");}}package com.mkf;import com.mkf.pattern.InterfaceOne;import com.mkf.pattern.impl.DecoratorOne;import com.mkf.pattern.impl.DecoratorThree;import com.mkf.pattern.impl.DecoratorTwo;import com.mkf.pattern.impl.Source;public class TestDecorator {/** * @param args */public static void main(String[] args) {Source s = new Source();InterfaceOne io = new DecoratorOne(new DecoratorTwo(new DecoratorThree(s)));io.operation();}}

?

输出结果:

?

DecoratorOne 增强功能前
DecoratorTwo 增强功能前
DecoratorThree 增强功能前
源被调用:com.mkf.pattern.impl.Source
DecoratorThree 增强功能后
DecoratorTwo 增强功能后
DecoratorOne 增强功能后

?

读书人网 >软件架构设计

热点推荐