Factory Method Pattern in COBOL

Continuing my series on design patterns for the COBOL, the next one on my list is the “Factory method” pattern.

The pattern is useful, as it helps you hide the real implementation/creation mechanism of your classes. I you are fond of uml… here is the actual uml (from wikipedia).

Factory Method Pattern from Wikipedia!

So… lets see the COBOL code…


interface-id. "Base".
method-id. "DoIt".
end method "DoIt".
end interface "Base".

class-id. "Derived1Impl".
object. implements type "Base".
method-id. "DoIt" public.
display "Derived1Impl from DoIt".
end method "DoIt".
end object.
end class "Derived1Impl".

class-id. "Derived2Impl".
object. implements type "Base".
method-id. "DoIt" public.
display "Derived2Impl from DoIt".
end method "DoIt".
end object.
end class "Derived2Impl".

class-id. "Factory".
object.
method-id. "GetObject".
linkage section.
01 obj-base type "Base".
procedure division using by value oType as binary-long
returning obj-base.

evaluate oType
when 1
set obj-base to new type "Derived1Impl"()
when 2
set obj-base to new type "Derived2Impl"()
when other
set obj-base to null
end method "GetObject".
end object.
end class "Factory".

class-id. "FactoryDemo".

method-id. "Main" static.
local-storage section.
01 obj-factory type "Factory".
01 base-obj type "Base".

linkage section.
01 args string occurs any.
procedure division using by value args.
set obj-factory to new type "Factory"()

set base-obj to obj-factory::"GetObject"(1)
invoke base-obj::"DoIt"()

set base-obj to obj-factory::"GetObject"(2)
invoke base-obj::"DoIt"()

end method "Main".
end class "FactoryDemo".

That was pretty straight forward… not too much pain…

And finally the code produces…


d:> FactoryDemo.exe
Derived1Impl from DoIt
Derived2Impl from DoIt
Hello world

Time to sign off for today.. but if you would like me to continue the series on code patterns or have a particular pattern you need… drop us a line!

This entry was posted in CLR, COBOL and tagged , , . Bookmark the permalink.