Singleton & "sequential execution" design patterns

1.1k Views Asked by At

I'm implementing a game library for mobile using Singleton design pattern as below

Game.initialize("game_id")
.downloadMap()
.showMap()
.setAutoAdjustMapResolution(true)

I have no problem with Singleton & Builder design pattern but my problem is

downloadMap() -> need to wait until initialize("game_id") // Network request
showMap -> waits until downloadMap() finishes// Network request
showMap -> depends on setAutoAdjustMapResolution(true)

I don't know what kind of design pattern I can apply in this case I'm thinking of Chain of Responsibility but no sure

Please give me your idea or advice. Thank you

1

There are 1 best solutions below

1
On

You are using chaining but this is totally different from Chain of Responsibility pattern.

The idea with Chain of Responsibility is that one task only is executed. There are several objects in a linked list (chain) each of which may execute the task depending on specific conditions. The user issues execute() method on at the head of the chain. If the conditions are not right, the first object will not execute() but instead will pass to the next object in the chain, and so on until one of them successfully executes() and returns. I don't believe this is what you need.

If you want your tasks to execute to completion in a predefined sequence, you can use chaining (like you have done) or issue separate commands in sequence.

If you want your tasks to execute in some complicated order that many change depending on the outcome of previous commands you can use the State Pattern. This is simple and quite powerful, where each State object is capable of carry out a task and deciding which task to do next, depending on the outcome of its own task or perhaps depending on input from another source.

If you want all of your tasks to start simultaneously, not waiting for others to complete, then you need to use asynchronous programming. You did not say which programming language you are using, but in Javascript for example this can be done simply with promises and other constructs such as sync and await.

asynchronous programming in any language means executing multiple tasks in separate threads or processes. This can be simple or complicated depending on what is being programmed and how separate the tasks are. Tasks may need to be synchronised at certain points or may need to use locks and other means if they using shared resources (such as a database printer) or updating shared resources (such as a file or a database record).

I hope this helps a bit but if you need more detail just ask, or provide more detail about our specific situation.