2020.05.06 【ABAP随笔】- ABAP工具类-CL_OBJECT_COLLECTION
本文参考Jerry Wang的程序学习了使用abap来实现java中ArrayList的功能,参考文章
SAP ABAP里存在Java List这种集合工具类么?CL_OBJECT_COLLECTION了解一下
代码
代码我是写在了本地,以便更容易看懂
REPORT ztest_polymorphism.
"定义接口
INTERFACE zif_shape.
METHODS get_area
RETURNING
VALUE(rv_result) TYPE float.
ENDINTERFACE.
"定义计算圆面积
CLASS zcl_circle DEFINITION.
PUBLIC SECTION.
INTERFACES zif_shape.
METHODS constructor
IMPORTING
!iv_radius TYPE float ."构造器,输入半径
PROTECTED SECTION.
PRIVATE SECTION.
DATA radius TYPE float .
ENDCLASS.
CLASS zcl_circle IMPLEMENTATION.
METHOD constructor.
me->radius = iv_radius.
ENDMETHOD.
METHOD zif_shape~get_area.
CONSTANTS: pai TYPE float VALUE '3.14'.
rv_result = pai * radius * radius.
ENDMETHOD.
ENDCLASS.
"定义计算矩形面积
CLASS zcl_rectangle DEFINITION.
PUBLIC SECTION.
INTERFACES zif_shape.
METHODS constructor
IMPORTING
!iv_height TYPE float
!iv_width TYPE float .
PROTECTED SECTION.
PRIVATE SECTION.
DATA height TYPE float .
DATA width TYPE float .
ENDCLASS.
CLASS zcl_rectangle IMPLEMENTATION.
METHOD constructor.
height = iv_height.
width = iv_width.
ENDMETHOD.
METHOD zif_shape~get_area.
rv_result = width * height.
ENDMETHOD.
ENDCLASS.
"定义计算三角形面积
CLASS zcl_triangle DEFINITION.
PUBLIC SECTION.
INTERFACES zif_shape.
METHODS constructor
IMPORTING
!iv_side TYPE float
!iv_height TYPE float .
PROTECTED SECTION.
PRIVATE SECTION.
DATA side TYPE float .
DATA height TYPE float .
ENDCLASS.
CLASS zcl_triangle IMPLEMENTATION.
METHOD constructor.
side = iv_side.
height = iv_height.
ENDMETHOD.
METHOD zif_shape~get_area.
rv_result = ( 1 / 2 ) * side * height.
ENDMETHOD.
ENDCLASS.
TYPES: BEGIN OF ty_shape,
shape TYPE REF TO object,
END OF ty_shape.
TYPES: tt_shape TYPE STANDARD TABLE OF ty_shape.
DATA: lt_shape TYPE tt_shape,"定义一个内表来存放不同的实例
lv_result TYPE float.
START-OF-SELECTION.
"借助CL_OBJECT_COLLECTION, 采取面向对象编程里多态(Polymorphism)的思路
DATA(lo_container) = NEW cl_object_collection( ).
DATA(lo_circle) = NEW zcl_circle( 1 ).
lo_container->add( lo_circle )."
DATA(lo_rectangle) = NEW zcl_rectangle( iv_width = 1 iv_height = 2 ).
lo_container->add( lo_rectangle ).
DATA(lo_triangle) = NEW zcl_triangle( iv_height = 2 iv_side = 3 ).
lo_container->add( lo_triangle ).
DATA(lo_iterator) = lo_container->get_iterator( )."获取了一个迭代器
WHILE lo_iterator->has_next( )."CL_OBJECT_COLLECTION_ITERATOR
DATA(lo_shape) = CAST zif_shape( lo_iterator->get_next( ) )."根据不同的类,返回值
lv_result = lv_result + lo_shape->get_area( ).
ENDWHILE.
WRITE:/ lv_result."圆,三角形,长方形的合计值
"这里可以实现将不同的实例加入到LT_SHAPE内表中,
DATA(entry) = VALUE ty_shape( shape = lo_circle ).
APPEND entry TO lt_shape.
entry = VALUE ty_shape( shape = lo_rectangle ).
APPEND entry TO lt_shape.
entry = VALUE ty_shape( shape = lo_iterator ).
APPEND entry TO lt_shape.
CLEAR lv_result.
LOOP AT lt_shape REFERENCE INTO DATA(lr_shape).
lo_shape = CAST zif_shape( lr_shape->shape ).
lv_result = lv_result + lo_shape->get_area( ).
ENDLOOP.
WRITE:/ lv_result."圆,三角形,长方形的合计值