在没必要改变原类文件和使用继承的状况下,动态地扩展一个对象的功能。它是经过建立一个包装对象,也就是装饰来包裹真实的对象。html
(1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加职责的对象。
(2)具体构件(Concrete Component)角色:定义一个将要接收附加职责的类。
(3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口,从外类来扩展Component类的功能,但对于Component类来讲,是无需知道Decorato的存在的。
(4)具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的职责。java
(1)装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。
(2)装饰对象包含一个真实对象的引用。
(3)装饰对象接受全部来自客户端的请求。它把这些请求转发给真实的对象。
(4)装饰对象能够在转发这些请求之前或之后增长一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就能够在外部增长附加的功能。在面向对象的设计中,一般是经过继承来实现对给定类的功能扩展。设计模式
(1)须要扩展一个类的功能,或给一个类添加附加职责。
(2)须要动态的给一个对象添加功能,这些功能能够再动态的撤销。
(3)须要增长由一些基本功能的排列组合而产生的很是大量的功能,从而使继承关系变的不现实。
(4)当不能采用生成子类的方法进行扩充时。一种状况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增加。另外一种状况多是由于类定义被隐藏,或类定义不能用于生成子类。ide
package com.ixunm.decorate; /** * 抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象 */ public interface Component { // 简单操做方法 public void sampleOperation(); }
package com.ixunm.decorate; /** * 具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。 */ public class ConcreteComponent implements Component{ @Override public void sampleOperation() { // 写相关的业务代码 System.out.println("具体对象操做"); } }
package com.ixunm.decorate; /** * 装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。 */ public class Decorator implements Component{ private Component component; /** * 构造方法初始化抽象构件对象 * @param component */ public Decorator(Component component) { this.component = component; } @Override public void sampleOperation() { // 委派给构件对象处理 if (component != null) { component.sampleOperation(); } } }
package com.ixunm.decorate; /** * 具体装饰角色ConcreteDecorator01:本类的独有功能 * 具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。 */ public class ConcreteDecorator01 extends Decorator{ /** * 构造方法初始化抽象构件对象 * * @param component */ public ConcreteDecorator01(Component component) { super(component); } @Override public void sampleOperation() { super.sampleOperation(); // 执行原Component的sampleOperation()方法 // 本类的独有功能:写相关的业务代码 System.out.println("具体装饰对象ConcreteDecorator01的操做"); } }
package com.ixunm.decorate; /** * 具体装饰角色ConcreteDecorator02:本类的独有功能 * 具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。 */ public class ConcreteDecorator02 extends Decorator{ /** * 构造方法初始化抽象构件对象 * * @param component */ public ConcreteDecorator02(Component component) { super(component); } @Override public void sampleOperation() { super.sampleOperation(); // 执行原Component的sampleOperation()方法 // 本类的独有功能:写相关的业务方法,执行相关的业务 mySampleOperation(); } /** * 本类的独有功能 */ private void mySampleOperation() { System.out.println("具体装饰对象ConcreteDecorator02的操做"); } }
package com.ixunm.decorate; public class Demo { public static void main(String[] args) { ConcreteComponent concreteComponent = new ConcreteComponent(); ConcreteDecorator01 decorator01 = new ConcreteDecorator01(concreteComponent); ConcreteDecorator02 decorator02 = new ConcreteDecorator02(concreteComponent); decorator01.sampleOperation(); decorator02.sampleOperation(); } }
java中的io流的设计模式,用到装饰模式测试
www.cnblogs.com/wxgblogs/p/5649933.htmlthis