`

java 设计模式学习笔记九 decorator装饰模式

阅读更多



decorator装饰模式


动态的给一个对象添加一些额外的职责




示例代码:


/**
* 工作接口
*
* @time 下午11:25:59
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public interface Work {
public void insert();
}




/**
* 插入方形桩
* @time 下午11:29:08
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class SquarePeg implements Work {


@Override
public void insert() {
System.out.println("方形桩插入");
}
}




/**
* 装饰模式
*
* @time 下午11:30:48
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
@SuppressWarnings("rawtypes")
public class Decorator implements Work {
private Work work;


private ArrayList list = new ArrayList();


/**
* 构造器
*/
@SuppressWarnings("unchecked")
public Decorator(Work work) {
this.work = work;
list.add("挖坑");
list.add("钉木板");
}


@Override
public void insert() {
newMethod();
}


public void newMethod() {
otherMethod();
work.insert();
}


// 增加额外的功能


private void otherMethod() {
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
System.out.println(((String) iterator.next()) + "正在进行");
}
}
}






/**
* 测试装饰模式
*
* @time 下午11:40:07
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class TestDecorator {
public static void main(String[] args) {
Work squarePeg=new SquarePeg();
Work decorator=new Decorator(squarePeg);

decorator.insert();
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics