ABAP设计模式实例-创建型模式

前言

大家可以使用开源项目ABAPplantUML生成UML类图
代码仅是个人测试记录

实例源代码

单例模式

report ypwk_singleton.

class lcl_basic_singleton definition create private.
  public section.


    class-methods:get_instance
      returning value(ro_instance) type ref to lcl_basic_singleton.

    class-methods class_constructor.

    methods:set_name importing i_name type string,
      get_name returning value(r_name) type string.

  private section.
    class-data:mo_intance type ref to lcl_basic_singleton.

    data:mv_name type string.
endclass.

class lcl_basic_singleton implementation.
  method class_constructor.
    create object mo_intance."饿汉模式,取消改方法实施即为懒汉模式
  endmethod.
  method get_instance.
    if mo_intance is not bound.
      create object mo_intance.
    endif.

    ro_instance = mo_intance.
  endmethod.

  method set_name.
    me->mv_name = i_name.
  endmethod.

  method get_name.
    r_name = me->mv_name.
  endmethod.
endclass.

start-of-selection.

  data(lo_instance1) = lcl_basic_singleton=>get_instance( ).

  lo_instance1->set_name( 'name1').

  data(lo_instance2) = lcl_basic_singleton=>get_instance( ).

  data(lv_name2) = lo_instance2->get_name( ).

  write lv_name2.

工厂模式

interface if_cellphone.
  methods:ring.
endinterface.

class huawei definition.

  public section.
    interfaces:if_cellphone.

    methods:constructor.
endclass.

class huawei implementation.
  method constructor.
    write :/ '华为手机制造成功'.
  endmethod.
  method if_cellphone~ring.
    write:/ '华为手机响起铃声...'.
  endmethod.
endclass.

class xiaomi definition.
  public section.
    interfaces:if_cellphone.

    methods:constructor.
endclass.

class xiaomi implementation.
  method constructor.
    write :/ '小米手机制造成功'.
  endmethod.
  method if_cellphone~ring.
    write :/ '小米手机响起铃声...'.
  endmethod.
endclass.

class cellphone_factory definition.

  public section.
    methods: constructor,
             make_cellphone importing iv_type             type string
                    returning value(ro_cellphone) type ref to if_cellphone..
endclass.

class cellphone_factory implementation.
  METHOD constructor.
    WRITE :/ '手机工厂新建成功!!!'.
  ENDMETHOD.
  method make_cellphone.
    case iv_type.
      when 'MI'.
        create object ro_cellphone type xiaomi.
      when 'HW'.
        create object ro_cellphone type huawei.
      when others.
    endcase.
  endmethod.
endclass.

start-of-selection.

  data(lo_factory) = new cellphone_factory( ).

  data(lo_huawei) = lo_factory->make_cellphone( iv_type = 'HW').
  lo_huawei->ring( ).

  data(lo_xiaomi) = lo_factory->make_cellphone( iv_type = 'MI').
  lo_xiaomi-&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值