ABAP设计模式之---“简单工厂方法模式(Simple Factory Method Pattern)”

1. 定义

用一个静态的工厂方法 (Factory Method /CREATION Method) 实现类的实例化过程。

工厂方法是类实例化的唯一途径。

2. 解读

  • 隐藏了类实例化过程所需要知道的背景信息
  • 工厂方法可以更具有描述性
  • 使用类的过程,更接近于“开箱即用”(直接通过工厂方法拿到实例),而非去学习类的实例化条件(constructor)

3. 举例

*&---------------------------------------------------------------------*
*& Report zsimple_factory_method_pattern
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT zsimple_factory_method_pattern.

**********************************************************************
* Simple Factory Method Pattern / Creation Method
* 1) Class is defined as CREATE PRIVATE
* 2) CREATE Method is defined as CLASS-METHODS
* 3) As a result, constructor is hidden
**********************************************************************
CLASS lcl_rectangle DEFINITION FINAL CREATE PRIVATE.
  PUBLIC SECTION.
    CLASS-METHODS create
      IMPORTING
        iv_length          TYPE i
        iv_width           TYPE i
      RETURNING
        VALUE(ro_instance) TYPE REF TO lcl_rectangle.

    METHODS get_area_size
      RETURNING
        VALUE(rv_size) TYPE i.

  PRIVATE SECTION.
    METHODS constructor
      IMPORTING
        iv_length TYPE i
        iv_width  TYPE i.

    DATA mv_length TYPE i.
    DATA mv_width TYPE i.
ENDCLASS.

CLASS lcl_rectangle IMPLEMENTATION.
  METHOD constructor.
    mv_length = iv_length.
    mv_width = iv_width.
  ENDMETHOD.

  METHOD create.
    ro_instance = NEW lcl_rectangle( iv_length = iv_length iv_width = iv_width ).
  ENDMETHOD.

  METHOD get_area_size.
    rv_size = mv_length * mv_width.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.

  DATA(lo_rectangle) = lcl_rectangle=>create(  iv_length = 3 iv_width = 2 ).
  DATA(lv_size) = lo_rectangle->get_area_size(  ).
  WRITE |The rectangle size is | && lv_size.

>本博客专注于技术分享,干货满满,持续更新。
>欢迎关注❤️、点赞、转发!

你可能感兴趣的:(设计模式,sap,abap,设计模式,工厂方法模式)