`

Decorator Pattern(装饰模式)

阅读更多

定义:  动态的给一个对象增加其他职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更灵活。

 

Sitemesh框架就是应用了装饰模式,Sithmesh是一个非常优秀的页面修饰框架,使用它可以动态的给页面加一些装饰,可以完全的代替所有的include指令。

 

装饰模式中类和对象的关系为:

  1. Component抽象构件:定义对象的接口,可以给这些对象动态增加职责(方法)

  2. ConcreteComponent 具体构件:定义具体的对象,Decorator可以给它增加额外的职责(方法)

  3. Decorator 装饰角色: 持有具体构件类的对象,以便执行原有功能

  4. ConcreteDecorator具体装饰: 具体扩展的功能在这里

 

应用情景:

  1. 你想透明的并且动态的给对象增加心的职责(方法),而有不会影响其他的对象

  2. 你给对象增加的职责在未来会放生变化

 

下面就是一个简单的装饰模式的例子:以吃饭为例,现在要增加一些功能,在吃饭前加听音乐,吃饭后加唱歌(当然这也可以用动态代理来实现)

 

抽象构件

package com.lbx.component;

/*
 * 抽象构件
 */

public interface Component {
	
	public void eat();
	
}

 

具体构件

package com.lbx.conceteComponent;

import com.lbx.component.Component;

/**
 * 具体构件
 * @author Administrator
 *
 */

public class ConcreteComponent implements Component {

	public void eat() {
		System.out.println("吃饭");
	}

}

 

 

装饰角色

package com.lbx.decorator;

import com.lbx.component.Component;

/**
 * 装饰角色
 * @author Administrator
 *
 */

public class Decorator implements Component {

	private Component component;

	protected Decorator(Component component) {

		this.component = component;

	}

	@Override
	public void eat() {
		// TODO Auto-generated method stub
		this.component.eat();
	}

}

 

 

具体装饰1

package com.lbx.concreteDecorator;

import com.lbx.component.Component;
import com.lbx.decorator.Decorator;

/**
 * 具体装饰(这里演示了两种扩展的情况,听音乐+吃饭和吃饭+唱歌)
 * @author Administrator
 *
 */

public class ConcreteDecoratorListen extends Decorator {

	public ConcreteDecoratorListen(Component component) {
		super(component);
	}
	
	public void eat(){
		this.listen("听音乐");    //执行增加的功能
		super.eat();
	}
	
	private void listen(Object obj){
		System.out.println(obj);
	}

}

 

 

 

具体装饰2

package com.lbx.concreteDecorator;

import com.lbx.component.Component;
import com.lbx.decorator.Decorator;

public class ConcreteDecoratorSing extends Decorator {

	public ConcreteDecoratorSing(Component component) {
		super(component);
		// TODO Auto-generated constructor stub
	}

	public void eat() {

		super.eat();

		System.out.println(sing());   // 执行扩展功能

	}

	private String sing() {

		return "唱歌";

	}

}

 

 

测试方法 

package com.lbx.test;

import com.lbx.component.Component;
import com.lbx.conceteComponent.ConcreteComponent;
import com.lbx.concreteDecorator.ConcreteDecoratorListen;
import com.lbx.concreteDecorator.ConcreteDecoratorSing;

public class Test {
	
	public static void main(String[] args) {
		Component component = new ConcreteComponent();
		
		ConcreteDecoratorListen c = new ConcreteDecoratorListen(component);
		c.eat();
		
		ConcreteDecoratorSing c2 = new ConcreteDecoratorSing(component);
		c2.eat();
		
	}
	
}

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics