This website is not affiliated with, sponsored by, or approved by SAP AG.

Object instance creation within class

Development (ABAP Development WorkBench, ABAP/4 programming)

Moderators: Snowy, thx4allthefish, YuriT, Gothmog

Object instance creation within class

Postby q4u » Thu Jul 02, 2015 6:16 am

Hi,
The normal way I create an object and call a method is directly within a program:

Code: Select all
data: zobject type ref to zobject_class.
create object zobject.
zobject->do_something( ).
zobject->do_something_else( ).


However I've seen cases where the object is created within the class, through a method. So the code looks like this:
Code: Select all
data: zobject type ref to zobject_class
zobject = zobject_class=>get_instance( )
zobject->do_something( ).
zobject->do_something_else( ).


The get_instance method looks like:
Code: Select all
if instance is initial.
    create object instance.
  endif.
  e_instance = instance.


Where 'instance' is a private attribute of type zobject_class.

I was wondering if this second technique just a matter of coding preference, or are there particular advantages of coding it that way?

Thanks.
q4u
 
Posts: 439
Joined: Wed Mar 08, 2006 7:02 am

Re: Object instance creation within class

Postby Gothmog » Thu Jul 02, 2015 6:51 am

When you use such a factory method to get the instance, returning an instance from a static attribute or creating it if it's initial, you'll always get the same instance. In fact, there is only at most one instance of this class for your session.

It's ABAP OO's way to implement a singleton pattern.
68 74 74 70 3a 2f 2f 74 69 6e 79 75 72 6c 2e 63 6f 6d 2f 62 64 6f 37 6d 77 67
Gothmog
 
Posts: 1942
Joined: Wed Sep 12, 2007 4:46 am
Location: Probably not home

Re: Object instance creation within class

Postby q4u » Thu Jul 02, 2015 10:28 am

Ah I see. Thank-you.
q4u
 
Posts: 439
Joined: Wed Mar 08, 2006 7:02 am

Re: Object instance creation within class

Postby Gothmog » Thu Jul 02, 2015 10:51 am

Note that there are factory methods that are not intended to create singletons - see class CL_SALV_TABLE, for example.
It's mostly a design choice.
68 74 74 70 3a 2f 2f 74 69 6e 79 75 72 6c 2e 63 6f 6d 2f 62 64 6f 37 6d 77 67
Gothmog
 
Posts: 1942
Joined: Wed Sep 12, 2007 4:46 am
Location: Probably not home


Return to ABAP

Who is online

Users browsing this forum: No registered users and 8 guests





This website is not affiliated with, sponsored by, or approved by SAP AG.