created a Foo with a factorycreated a Bar with a factory
Ruby's blocks and Proc objects can also be used as factories. A block can create and return a new object. Code that uses the factorycan yield to the block, or call the proc, every time a new object is needed.
def create_something_with_blocknew_object = yieldputs "created a #{new_object.class} with a block"enddef create_something_with_proc( &proc )new_object = proc.callputs "created a #{new_object.class} with a proc"endcreate_something_with_block { Foo.new }create_something_with_block { Bar.new }create_something_with_proc { Foo.new }create_something_with_proc { Bar.new }
This produces the output:
created a Foo with a blockcreated a Bar with a blockcreated a Foo with a proccreated a Bar with a proc
Q: Ummm. Seems to me that you're specifying the concrete class name here:
create_something(Foo)
and
create_something(Bar)
. My understanding of Abstract Factory is that there's an additional level of indirection involved.A: The
create_something
method is creating objects through an abstract interface and does not have knowledge of concrete types.The code at the top level is selecting which factory object will be used by
create_something
. There always needs to be some part of the code that creates factories, and that part needs knowledge of concrete types. The use of the Abstract Factory method is to shieldthe rest of the code from that knowledge.I found interesting to redo the maze example from the DP book in ruby. Basically, just translated it is:
class MazeGamedef create_maze(factory)maze = factory.new_mazeroom1 = factory.new_room 1room2 = factory.new_room 2door = factory.new_door room1, room2maze.add room1maze.add room2room1.north= factory.new_wallroom1.east= doorroom1.south= factory.new_wallroom1.west= factory.new_wallroom2.north= factory.new_wallroom2.east= factory.new_wallroom2.south= factory.new_wallroom1.west= doorreturn mazeendend
Obviously, the new_xxx are simple to think as Xxx.new, as pointed above in this page, and the instance of a Factory can justbecome a class or module holding the various Xxx:
module DwemthyDungeonclass Maze...endend
Add a Comment