设计模式

装饰器模式

2019-06-01  本文已影响0人  78f6ced3a012

题外话:把技术点记录下来,只是为了理清思路,加深理解。让自己对知识点理解更加透彻,而使用到工作中合适的场景。

概述:‘装饰器模式’,从‘装饰器’三个字面意思,去靠近理解,此模式去装饰(包含)某个实体(类),使其和原来不一样(功能扩展,加强)。

比较:装饰器模式和继承一个类去扩展功能比较相似,但是装饰器模式不会破坏原有类的签名,而是一个新的类去包装原有的类。

代码:使用装饰器模式包装List类(给add()方法加强,给出提示)
装饰器类:

package com.example.java8.model.decoration;

import java.util.List;

/**
 * 装饰类
 * @param <T>
 */
public class DecorationList<T> {

    private List<T> list;

    public DecorationList(List<T> list) {
        this.list = list;
    }

    public boolean add(T t) {
        boolean flag = false;
        try {
            flag = this.list.add(t);
            System.out.println("添加成功");
        } catch (Exception e) {
            flag = false;
            System.out.println("添加失败");
        }
        return flag;
    }

}

测试类:

package com.example.java8.model.decoration;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class DecorationTest {

    @Test
    public void test() {
        List<String> list = new ArrayList<>();
        DecorationList<String> decorationList = new DecorationList<>(list);
        boolean add = decorationList.add("hello");
    }

}
上一篇 下一篇

猜你喜欢

热点阅读