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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值