【问题标题】:How to implement a list with decorated elements如何实现带有装饰元素的列表
【发布时间】:2022-09-27 19:21:16
【问题描述】:

有了 REST 或 JPA 查询的结果,我经常需要使用来自其他查询的一些附加属性来装饰项目。为了避免处理和处理列表(结果),我正在考虑一个运行时通用列表装饰器,它包含在运行时装饰的项目。

问题:是否有任何标准模式?

示例:作为 REST 查询的结果,我有人员列表。我需要用假期配额来装饰每个人。

多年来,我偶尔会搜索这种模式,但找不到任何东西。

    标签: java design-patterns decorator


    【解决方案1】:

    最后我创建了两个类来实现这个:

    @Dependent
    public abstract class ElementDecorator<E> {
        public abstract void wrap( E elem );
    }
    

    和

    @Dependent
    public class MyList<E extends ElementDecorator> extends AbstractList {
        
        private Log log = LogFactory.getLog( this.getClass() );
        private List list;
        private Class<E> clazz;
        private Annotation annotation;
        
        public MyList(){}
        
        public MyList( List oryList, Class<E> c ){
            list = oryList;
            clazz = c;
        }
        
        public MyList( List oryList, Class<E> c, Annotation a ){
            list = oryList;
            clazz = c;
            annotation = a;
        }
        
        @Override
        public E get( int index ){
            if( annotation == null )
                annotation = new AnnotationLiteral<Default>() {};
            E element = null;
            try{
                element = CDI.current().select( clazz, annotation ).get();
                element.wrap( list.get( index ) );
            }catch( Exception e ){
                log.error( e.getMessage() );
            }
            return element;
        }
        
        public int size(){
            return list.size();
        }
    
    }
    

    现在,每当我需要一个装饰元素列表时,我都会使用以下方法扩展 ElementDecorator:

    @Dependent
    @Default
    public class AppointmentDecorator extends ElementDecorator<Appointment> implements Serializable {
        
        private Log log = LogFactory.getLog( this.getClass() );
        private @Inject SmCostDao smCostDao;
        private Appointment appointment;
        
        @Override
        public void wrap( Appointment a ){
            appointment = a;
        }
        
        public Appointment getAppointment(){
            return appointment;
        }
        
        public String getCostCorrected(){
            SmCost smcost = smCostDao.findBy(appointment.getKey());
            smcost.getCost();
        }
        
    }
    

    我可以实例化: MyList( oryginalList, AppointmentDecorator )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 2018-06-17
      • 1970-01-01
      • 2021-04-11
      • 2012-01-29
      • 2013-07-25
      相关资源
      最近更新 更多