设计模式-7-装饰器模式

来源:互联网 发布:手机微信无法连接网络 编辑:程序博客网 时间:2024/06/05 06:59

装饰器模式:允许向一个现有的对象添加新的功能,同时又不改变其结构。他作为一个现有的类的封装。



1.定义一个接口作为原始类

package com.structuralPattern.decorator.edition1;public interface Primitive {void operation();}

2.Source类继承Primitive并实现operation方法

package com.structuralPattern.decorator.edition1;public class Source implements Primitive{@Overridepublic void operation() {System.out.println("原始类的方法");}}

3.定义装饰器类(明显Decorator中使用了“对象适配器模式”,通过定义变量primitive类承接Source的实例,利用构造函数进行初始化)

package com.structuralPattern.decorator.edition1;public class Decorator implements Primitive {public Primitive primitive;public  Decorator(Primitive primitive) {this.primitive = primitive;}@Overridepublic void operation() {}}

4.定义实际装饰器

package com.structuralPattern.decorator.edition1;public class Decorator1 extends Decorator{public Decorator1(Primitive primitive) {super(primitive);}@Overridepublic void operation() {System.out.println("第一个装饰器前--添加的新功能");primitive.operation();System.out.println("第一个装饰器后--添加的新功能");}}

package com.structuralPattern.decorator.edition1;public class Decorator2 extends Decorator{public Decorator2(Primitive primitive) {super(primitive);}@Overridepublic void operation() {System.out.println("第二个装饰器前--添加的新功能");primitive.operation();System.out.println("第二个装饰器后--添加的新功能");}}

package com.structuralPattern.decorator.edition1;public class DecoratorTest {public static void main(String[] args) {Primitive primitive = new Source();//装饰类对象Primitive pd1 = new Decorator1(primitive);pd1.operation();//装饰类对象Primitive pd2 = new Decorator1(primitive);pd2.operation();System.out.println("============");Primitive pd = new Decorator1(new Decorator2(primitive));pd.operation();}}







原创粉丝点击