[关键字]:java,design pattern,设计模式,《Java与模式》学习,decorator,装饰模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com)
[正文]:
package pattern.decorator;
/**
* 装饰模式:Decorator Pattern
* @version 2009-6-5
* @author Winty(wintys@gmail.com)
*/
public class DecoratorTest{
public static void main(String[] args){
Component component;
component = new ConcreteComponent();
component.doSomething();
System.out.println("");
//透明的装饰模式
Component decorator;
decorator = new ConcreteDecorator(component);
decorator.doSomething();
System.out.println("");
//半透明的装饰模式
ConcreteDecorator decorator2;
decorator2 = new ConcreteDecorator(component);
decorator2.doSomething();
decorator2.doOtherThings();
}
}
/**
* 抽象构件:Component
*/
interface Component{
public abstract void doSomething();
}
/**
* 具体构件:ConcreteComponent
*/
class ConcreteComponent implements Component{
@Override
public void doSomething(){
System.out.println("do something");
}
}
/**
* 装饰:Decorator
*/
abstract class Decorator implements Component{
private Component comp;
public Decorator(Component comp){
this.comp = comp;
}
@Override
public void doSomething(){
comp.doSomething();
}
}
/**
* 具体装饰:ConcreteDecorator
*/
class ConcreteDecorator extends Decorator{
public ConcreteDecorator(Component comp){
super(comp);
}
@Override
public void doSomething(){
super.doSomething();
doMoreThings();
}
private void doMoreThings(){
System.out.println("do more things.");
}
/**
* 新增的方法不是Component接口的一部分,
* 所以不能通过Component接口透明地访问。
*/
public void doOtherThings(){
System.out.println("do other things.");
}
}
posted on 2009-06-07 22:33
天堂露珠 阅读(999)
评论(0) 编辑 收藏 所属分类:
Pattern