Iniciar Sesión

Ver la Versión Completa : [Duda] ¿Qué se hace en CLASS-OBJECT y FACTORY?


Kuk
25 de enero de 2017, 20:04
Amigos, me estoy metiendo en OO COBOL... :buzo: Sí sí, en OO COBOL porque lo necesito en el trabajo. Y necesito ayuda para entender algunas cosas. Por ejemplo, la diferencia de lo que se define en CLASS-OBJECT con lo que se define en OBJECT. También no he entendido bien lo que se hace en el FACTORY.

Eslopes, si no me equivoco tu eres bastante enterado en el tema. Necesito de tu sabiduría amigo :help: :sis:

Por cierto, Eslopes, ¿tu página de 100coolthings ya no funciona?

Kuk
27 de enero de 2017, 12:12
Acerca del FACOTRY he encontrado esto:

A factory method defines an operation that is supported by a class independently of any object instance of the class.
COBOL factory methods are equivalent to Java public static methods.

Información completa: IBM Knowledge Center (http://www.ibm.com/support/knowledgecenter/en/SS6SG3_3.4.0/com.ibm.entcobol.doc_3.4/tpoot45.htm)

Dasije
27 de enero de 2017, 17:12
Sí es desde PowerCOBOL.

CLASS-OBJECT, son las métodos de un objeto, es una forma de referirse a él.

El OO COBOL se utiliza para crear activex o objetos con classes como pueden ser métodos que puedes invocar dentro de tus programas, de hay el nombre Oriented Object.

Kuk
27 de enero de 2017, 22:33
Dasije, el OO COBOL es OO como cualquier otro lenguaje, puedes hacer muchísimas cosas, entre otras invocar clases de Java o crear clases de COBOL que serán invocadas desde Java y etc.

La pregunta es, cual es la diferencia entre CLASS-OBJECT y OBJECT.

En este caso yo estoy trabajando en Visual COBOL de MicroFocus, no estoy hablando de PowerCOBOL. Aunque la sintaxis de puro OO COBOL es la misma (o casi la misma).

Eslopes
30 de enero de 2017, 17:04
OBJECT é onde definimos os métodos e propriedades da instância
FACTORY é onde definimos métodos e propriedades estáticos.

Saludos, Emerson

Kuk
31 de enero de 2017, 08:42
Eslopes, ¿entonces qué es la sección OBJECT que está aparte?
Mira este ejemplo, línea 60 contiene CLASS-OBJECT y la línea 86 contiene OBJECT sólo:


copy "guibase.if". *> Standard interface to GUIBase class using vocabulary generator - You can just invoke GUIBase methods directly if you wish.
*>-------------------------------------------------------------- *>
*> Combo Box Demonstration Class : *>
*> *>
*> This is a modal Dialog Box. The dialog box has been created *>
*> using the Dialog Editor. This class demonstrates how to use 3 *>
*> types of Selection boxes within your program - In *>
*> Particular : *>
*> *>
*> - How to display selection (combo) boxes - *>
*> Simple, Dropdown(drop) and Droplist *>
*> - How to insert items in combobox controls prior to display *>
*> - How to obtain user selections on each combo box *>
*> - How to display strings of text within a message Box. *>
*> *>
*> Screen Controls Used : *>
*> *>
*> Pushbuttons - To perform Actions *>
*> Simple Combo Box - To populate an entry field with a value, *>
*> or select an item from a list *>
*> Drop Combo Box - To populate an entry field with a value *>
*> or select an item from a list which is only *>
*> displayed if the user selects it. *>
*> DropList Combo Box - To populate an entry field with a *>
*> selection from a list. *>
*> MessageBox - To display the selected values from the *>
*> combo boxes. *>
*> The code in this class has been heavily commented, and further *>
*> explanations are given as in-line comments in columns 73 *>
*> Onwards. *>
*> *>
*> Copyright (C) 1996-2000 Micro Focus International Ltd.
*>-------------------------------------------------------------- *>
*>
*>------------------<CLASSS PROGRAM DEFINITION>----------------- *>
class-id. ComboBoxDemo *> Declare the name of this class.
data is private *> Declares that children of this class do not have access to it's data
inherits from modal. *> Forces this class to inherit the behaviour of the modal class from the class library. This implies that the dialog boxes created will be modal, I.E. you cannot move to other areas
*> of the application whilst a dialog box created by this class is active
*>
Object Section. *> Class Objects
*>
class-control. *> Declare the classes that this class uses directly
CharacterArray is class "chararry" *> From the class library - Used for translating strings to objects
OrderedCollection is class "ordrdcll" *> From the class library - Used to create collections of objects - similar to an array where data is stored in the order in which it was added to the array.
SortedCollection is class "srtdclln" *> From the class library - Used to create collection of objects which may be sorted - usually alphabetically
Module is class "module" *> From the class library - Used to wrap classes that may contain resources - I.E. GUI objects in a DLL file
MessageBox is class "msgbox" *> From the class library - we use this class for creating and handling message boxes
ComboBoxDemo is class "combobox" *> Our own class
Modal is class "modal" *> From the class library - we use this class to create and control a modal dialog box
. *>
*>
*>------------------<COMMON CLASS & INSTANCE DATA>-------------- *>
working-storage section. *> Declare the data that can be accessed from both the class and instances of the class
*> Copy Files *>
copy "mfres.cpy". *> Copy file created by resource manager containing control names and symbol numbers
copy "p2cevent.cpy". *> Panels2 copy file containing level 78 items used to identify events
*>
*>------------------<CLASS DEFINITION>-------------------------- *>
class-Object. *> Class data and methods start here
*>
*>------------------<COMMON CLASS & INSTANCE DATA>-------------- *>
object-storage section. *> None required within this class
*>
*>------------------<CLASS METHODS>----------------------------- *>
method-id. "ShowDemo". *> The calling class invokes and executes this method to create and run the groupbox dialog
*>
local-storage section. *>
01 lsid pic x(4) comp-5. *> Unique identifier for this dialog box
01 lsDialog object reference. *> Used as an object handle to the dialog which this class creates
*>
linkage section. *> Data passed from the invoking class
01 lnkParent object reference. *> The resource .dll file containing the dialog box GUI object
01 lnkResource object Reference. *> The parent of this dialog box, in this case another dialog box
procedure division using lnkParent lnkResource. *> The executable code of the Run method
move combo-box-screen to lsId *> Unique identifier for this dialog box using the symbol number for the dialog within the resource copy file
invoke self "fromResource" using lnkParent lnkResource *> Locates the required Groupbox dialog box within the resource file, and creates it as an object (lsdialog) that we can then use
lsid returning lsDialog *>
invoke lsdialog "create" *> Initialize above created (lsdialog) instance object, which sets up the initial state of the dialog and events
invoke lsdialog "show" *> Make the dialog visible, giving control to the eventmanager, and await user input.
exit method. *>
end method "ShowDemo". *> End of "ShowDemo" Method
end class-object. *> End of class data and methods
*>
*>------------------<INSTANCE DEFINITION>----------------------- *>
object. *> Instance Data and Methods start here
*>
*>------------------<INSTANCE DATA>----------------------------- *>
object-storage section. *> Data declared here is visible throughout the scope of this class
01 SimpleComboItem object reference. *> Used as an object handle to the Simple combo box item which will be created as a control within lsdialog by this class
01 DropComboItem object reference. *> Used as an object handle to the Drop combo box item which will be created as a control within lsdialog by this class
01 DropListComboItem object reference. *> Used as an object handle to the Droplist combo box item which will be created as a control within lsdialog by this class
*>------------------<INSTANCE METHODS>-------------------------- *>
*>-------------------------------------------------------------- *>
method-id. "Create". *> instance Method invoked by the class method "RUN"
procedure division. *>
invoke super "create" *> invoke the inherited method to invoke and initialize the class
invoke self "LinkScreenEventsToMethods" *> Invoke method to map events to methods within this class
invoke self "LinkControlsToProgramFields" *> Invoke method to obtain object handles to the controls on the dialog for this class
invoke self "InitializeControls" *> Invoke method to intialize the screen controls, in particular, to populate the combo boxes with values
exit method. *> Return control to the class method "RUN"
end method "Create". *> End of "CREATE" method
*>-------------------------------------------------------------- *>
*>
method-id. "LinkScreenEventsToMethods". *> Instance method invoked from the create instance method "RUN"
local-storage section. *> Contains data private to this method
01 lsId pic x(4) comp-5. *> Unique identifier for this dialog box
01 lsPushbutton object reference. *> Object reference item used for storing object handles to push button controls on our dialog
*>
procedure division. *>
*> Cancel Button. *>
move idCancel to lsId *> Pick up the symbol number for the cancel control for our dialog
invoke self "GetObjectFromId" using lsId *> Obtain an object reference to the cancel control for our dialog, using the cancel control's symbol number
returning lsPushbutton *>
map event clicked upon lspushbutton to method *> Use the GUIBase Map method to link the event "clicked" upon our cancel pushbutton control to
z"OnEventCancel" upon self *> the method "Oncancel" within this class
*> OK Button *>
move IDOK to lsId *> Similar processing as for Cancel button
invoke self "GetObjectFromId" using lsId *>
returning lsPushbutton *>
map event clicked upon lspushbutton to method *>
z"OnEventOK" upon self *>
*> Dialog Close icon *>
map event closed upon self to method *> For the close icon on the dialog, we don't need to obtain an object handle to it, as it is part of the dialog.
z"OnEventCancel" upon self *> in this case, we have mapped the dialog close to the same method as the cancel pusbutton.
exit method. *> Return control to the class method "RUN"
end method "LinkScreenEventsToMethods". *> End of method
*>-------------------------------------------------------------- *>
*>
method-id. "LinkControlsToProgramFields". *> Instance method invoked from the class instance method "RUN"
local-storage section. *> Contains data private to this method
01 lsId pic x(4) comp-5. *> Unique identifier for this dialog box
procedure division. *>
move simple-combo-box to lsid *> Obtain symbol number for the simple combo box
invoke self "getobjectfromid" using lsId *> Obtain an object handle for the simple combo box
returning SimpleComboItem *>
move drop-combo-box to lsid *> Obtain symbol number for the drop combo box
invoke self "getobjectfromid" using lsId *> Obtain an object handle for the drop combo box
returning DropComboItem *>
move droplist-combo-box to lsid *> Obtain symbol number for the droplist box
invoke self "getobjectfromid" using lsId *> Obtain an object handle for the droplist combo box
returning DropListComboItem *>
exit method. *> Return control to the class method "RUN"
end method "LinkControlsToProgramFields". *> End of Method
*>-------------------------------------------------------------- *>
*>
method-id. "InitializeControls". *> Instance method invoked from the class instance method "RUN"
local-storage section. *> Contains data private to this method
01 aCollection object reference. *> Object handle to the collection used to populate each combo selection box
procedure division. *>
invoke self "PreDisplayList" returning aCollection *> Invoke the Predisplaylist method within this class to populate the simple combo box
invoke SimpleComboItem "setcontents" using aCollection *> Sets the contents of the combo box to those of the sorted collection
invoke DropComboItem "setcontents" using aCollection *> Sets the contents of the combo box to those of the sorted collection
invoke DropListComboItem "setcontents" using aCollection *> Sets the contents of the combo box to those of the sorted collection
invoke aCollection "deepfinalize" returning aCollection *> Destroys the collection and all objects which it contains
exit method. *> Return control to the class method "RUN"
end method "InitializeControls". *> End of Method
*>-------------------------------------------------------------- *>
*>
method-id. "OnEventOK". *> Instance method invoked when the OK pushbutton is pressed
working-storage section. *> Contains data required for this method
01 message-string. *> Data item used for the string passed to the message box containing the item within each combo box which the user selected
03 simplecombo-text pic x(19) *> String of text for titling the simple combo box value
value "Simple box Value : ". *>
03 simplecombovalue pic x(10). *> Stores the user selected value for the simple combo box
03 simple-terminate pic xx value is x"0D0A". *> Carriage return line feed required to force line seperation in the displayed message box
03 dropcombo-text pic x(17) *> String of text for titling the drop combo box value
value "Drop box Value : ". *>
03 dropcombovalue pic x(10). *> Stores the user selected value for the drop combo box
03 dropcombo-terminate pic xx value is x"0D0A". *> Carriage return line feed required to force line seperation in the displayed message box
03 droplist-text pic x(21) *> String of text for titling the droplist combo box value
value "DropList box Value : ". *>
03 droplistcombovalue pic x(10). *> Stores the user selected value for the droplist combo box
03 droplist-terminate pic x value is x"00". *> Null termination of message-string to enable the string to be passed to the null terminated setmessage method of the message box class
local-storage section. *> Contains data private to this method
01 lsMsgBox object reference. *> The object handle to the message box
01 StringLength pic x(4) comp-5. *> Contains the length of string to be returned when using the getvaluewithsize method to accept the user selected input from each combo box
01 SimpleComboRef object reference. *> Object handle to the user selected input on the simple combo box
01 DropComboRef object reference. *> Object handle to the user selected input on the drop combo box
01 DropListComboRef object reference. *> Object handle to the user selected input on the droplist combo box
*>
procedure division. *>
invoke SimpleComboItem "gettext" returning SimpleComboRef *> Obtain an object handle to the user selected input within the simple combo box control
move length of SimpleComboValue to StringLength *> Move the maximum length of item that the combo box could contain, to stringlength
invoke SimpleComboRef "GetValueWithSize" using StringLength *> Extract the value (of length stringlength) of the users input within the simple combobox Using the object handle for the user selected input, placing it into the item
returning SimpleComboValue *> simplecombovalue
invoke DropComboItem "GetText" returning DropComboRef *> Obtain an object handle to the user selected input within the simple combo box control
move length of DropComboValue to StringLength *> Move the maximum length of item that the combo box could contain, to stringlength
invoke DropComboRef "GetValueWithSize" using StringLength *> Extract the value (of length stringlength) of the users input within the simple combobox Using the object handle for the user selected input, placing it into the item
returning DropComboValue *> dropcombovalue
invoke DropListComboItem "GetText" returning DropListComboRef *> Obtain an object handle to the user selected input within the simple combo box control
move length of DropListComboValue to StringLength *> Move the maximum length of item that the combo box could contain, to stringlength
invoke DropListComboRef "GetValueWithSize" using StringLength *> Extract the value (of length stringlength) of the users input within the simple combobox Using the object handle for the user selected input, placing it into the item
returning DropListComboValue *> droplistcombovalue
invoke MessageBox "new" using self returning lsMsgBox *> Create an instance of the messagebox class (from the GUI class library) returning an object handle to it
*> Note - the message box to be displayed will have default properties - I.E. and OK button.
invoke lsMsgBox "SetTitlez" using *> Set the title of the message box to the contents of a null terminated string
z"User Selections From Combination Selection Boxes" *>
invoke lsMsgBox "setMessagez" using Message-String *> Set the message to be displayed within the message box to be the null terminated string message-string (note method used is setmessageZ)
invoke lsMsgBox "show" *> Display the message box, passing control to the event manager, which will await the user pressing the OK button before control will return to the next statement in this method
invoke lsMsgBox "finalize" returning lsMsgBox *> Remove all object references used by the message box
exit method. *> Return control to the eventmanger, which will continue to poll for events on our dialog
end method "OnEventOK". *> End of method
*>-------------------------------------------------------------- *>
*>
exit method. *> Return control to the calling method
end method "PreDisplayList". *> End of method
*>-------------------------------------------------------------- *>
*>
end object. *> End of instance and data methods
end class ComboBoxDemo. *> End of this class



Aquí tenemos class-Object (Class data and methods start here) y object (Instance Data and Methods start here). ¿Cómo se puede declarar un método a una instancia que no existe aún? Porque la instancia la obtendremos creándola a partir de la clase. Y cómo asociaríamos ese método de instancia a una instancia que se crea en dinámico (claramente)... :tonto:

Me estoy liando con esto, a ver si lo puedes explicar bien.

Eslopes
31 de enero de 2017, 10:27
Ah, Micro Focus, por que simplificar se podemos complicar? :P

class-object é o equivalente a factory nesta sintaxe da Micro Focus.
object são os métodos da instância. Os comentários no código estão confusos, aliás todo código da Micro Focus é confuso porque a MF insiste em tentar reescrever o Cobol. Neste ponto a Fujistu era muito melhor.

O exemplo abaixo é compliant com o ANSI 2002 e veio do próprio site da MF. Veja se esclarece:


class-id. Example inherits
from Base.
environment division.
...
configuration section.
repository.
class Example as "exmp"
class Base as "base"
class CharacterArray.

...
factory. *> CLASS-OBJECT
data division.
working-storage section.
...
method-id. "newWithData".
...
end method "newWithData".
end-factory. *> END CLASS-OBJECT.

object.
working-storage section.
...
method-id. "sayHello".
...
end method "sayHello".
end object.
end class Example.

Kuk
31 de enero de 2017, 13:46
Eslopes, gracias por la aclaración. Efectivamente, en este otro ejemplo de MF usan FACTORY y no CLASS-OBJECT:


cbl dll,thread,pgmname(longmixed),lib
Identification Division.
Class-id. Account inherits Base.
Environment Division.
Configuration section.
Repository.
Class Base is "java.lang.Object"
Class Account is "Account".
*
Identification division.
Factory.
Data division.
Working-storage section.
01 NumberOfAccounts pic 9(6) value zero.
*
Procedure Division.
*
* createAccount method to create a new Account
* instance, then invoke the OBJECT paragraph's init
* method on the instance to initialize its instance data:
Identification Division.
Method-id. "createAccount".
Data division.
Linkage section.
01 inAccountNumber pic S9(6) binary.
01 outAccount object reference Account.
* Facilitate access to JNI services:
Copy JNI.
Procedure Division using by value inAccountNumber
returning outAccount.
* Establish addressability to JNI environment structure:
Set address of JNIEnv to JNIEnvPtr
Set address of JNINativeInterface to JNIEnv
Invoke Account New returning outAccount
Invoke outAccount "init" using by value inAccountNumber
Add 1 to NumberOfAccounts.
End method "createAccount".
*
End Factory.
*
Identification division.
Object.
Data division.
Working-storage section.
01 AccountNumber pic 9(6).
01 AccountBalance pic S9(9) value zero.
*
Procedure Division.
*
* init method to initialize the account:
Identification Division.
Method-id. "init".
Data division.
Linkage section.
01 inAccountNumber pic S9(9) binary.
Procedure Division using by value inAccountNumber.
Move inAccountNumber to AccountNumber.
End method "init".
*
* getBalance method to return the account balance:
Identification Division.
Method-id. "getBalance".
Data division.
Linkage section.
01 outBalance pic S9(9) binary.
Procedure Division returning outBalance.
Move AccountBalance to outBalance.
End method "getBalance".
*
* credit method to deposit to the account:
Identification Division.
Method-id. "credit".
Data division.
Linkage section.
01 inCredit pic S9(9) binary.
Procedure Division using by value inCredit.
Add inCredit to AccountBalance.
End method "credit".
*
* debit method to withdraw from the account:
Identification Division.
Method-id. "debit".
Data division.
Linkage section.
01 inDebit pic S9(9) binary.
Procedure Division using by value inDebit.
Subtract inDebit from AccountBalance.
End method "debit".
*
* print method to display formatted account number and balance:
Identification Division.
Method-id. "print".
Data division.
Local-storage section.
01 PrintableAccountNumber pic ZZZZZZ999999.
01 PrintableAccountBalance pic $$$$,$$$,$$9CR.
Procedure Division.
Move AccountNumber to PrintableAccountNumber
Move AccountBalance to PrintableAccountBalance
Display " Account: " PrintableAccountNumber
Display " Balance: " PrintableAccountBalance.
End method "print".
*
End Object.
*
End class Account.


MF es muy permisivo, le pasas una poesía y lo compila también. :D Demasiado liberal, en mi opinión.

CONCLUSIÓN: Class-Object y Factory son exactamente lo mismo, dependiendo del compilador que se use. En Fujitsu hay que siempre utilizar FACTORY, en MF se puede utilizar ambos.

Eslopes, corrígeme si algo no es correcto.

Eslopes
2 de febrero de 2017, 00:22
Olá, sobre o site 100coolthings, desde que saí da IBM no ano passado desliguei sites que não geravam $$$. O 100coolthings era para ter se tornado um livro sobre OO Cobol, mas a falta de interesse das pessoas sobre o tema me desanimou. OO Cobol é um tipo de tecnologia que faz sentido no ambiente Cobol, mas Cobol não faz mais sentido para ninguém (exceto os poucos entusiastas da linguagem).

Saludos

Kuk
2 de febrero de 2017, 08:36
Eslopes, yo estoy bastante interesado! Así que todo lo que puedas contarnos, bienvenido es! Tienes este Foro para poner ejemplos y explicar todo lo que creas necesario sobre el tema. ;)

Nitzer
2 de febrero de 2017, 09:30
Increibles aportaciones. A veces nos olvidamos de todo lo que se puede conseguir con Cobol. Estamos demasiado centrados en programar nuestro negocio.

Eslopes
2 de febrero de 2017, 14:26
Olá,

eu havia publicado no meu site coisas como design patterns, integração com Java, com GoogleMaps, OO Cobol e VB Script, exemplos de diversas coisas. Acho que meu erro foi ter publicado em inglês.

Ainda dá para ver algo online no webarchive

Site sobre OO Cobol
(https://web.archive.org/web/20160109031551/http://100coolthings.net/)

Saludos, Emerson

Kuk
2 de febrero de 2017, 15:07
Eslopes, a mi no se me abre la página...

Yo insisto en que el tema es muy interesante. Sería una pena que tanto material se pierda. Amigo Eslopes, cuando puedas estaría bien que vayas publicando aquí en el Foro cosas que tenías en esa WEB. Personalmente yo te lo agradecería :bien::yupi:

Nitzer
4 de febrero de 2017, 20:28
Eslopes, opino como Kuk, sería una verdadera pena perder toda esa información y la página no va :(

Kuk
22 de febrero de 2017, 15:49
Eslopes, en este código usas STATIC:


CLASS-ID. Singleton AS "CoolThings.Singleton".

*> Static data and methods
static.
data division.
working-storage section.
01 instance usage object reference SINGLETON is private.

procedure division.
method-id. GetInstance AS "GetInstance".
data division.
linkage section.
01 localSingleton usage object reference SINGLETON.

procedure division returning localSingleton.
if (instance equal null) then
invoke Singleton "NEW" returning localSingleton
set instance to localSingleton
else
set localSingleton to instance
end-if

end method GetInstance.
end static.

*> Instance's data and methods
object.
environment division.
data division.
working-storage section.
01 counter pic s9(04) value zeros.

procedure division.
method-id. NEW is private.
data division.
procedure division.
move zeros to counter.

end method NEW.

method-id. GetCounter as "GetCounter".
data division.
linkage section.
01 localCounter pic s9(04).

procedure division returning localCounter.
add 1 to counter.

move counter to localCounter.

end method GetCounter.

end object.

END CLASS Singleton.


Entiendo que en el dialecto de Fujitsu OO COBOL, STATIC equivale a FACTORY. ¿Es esto cierto?