Design pattern for an object that behaves differently when clicked, depending on the global state

I am using Unity3D for this question, but this is a general software development issue.

Objects (interactive objects) in Unity3D are built with components or behavior. By combining the behavior with each other, you determine the exact behavior of the object.

I reflect on how different objects react differently when they click, based on the global state. For example, I have a tool that targets only circles around the scene; if I select this tool and click on the object, and if it is a circle, I will change it to a square. If it is not a circle, I will simply ignore it.

Using a component-based object design, I would define a behavior called IsCircle, and when it is clicked, I will check what should happen to it. However, what is the best way to access the global state of the entire application? Let's say I want to avoid any switch if-else, and I want the solution to be untied

(The problem is that the OnMouseDown () event handler does not pass any parameters).

I would appreciate it if the answer would mean the environment that I am using applies a compound template.

+4
source share
3 answers

Maybe something like Observer could help? All components that must change their behavior based on the global state register for an object, such as ScreenManager , and whenever the global state changes, you notify all components that are registered at this moment of change, and accordingly change their state.

-1
source

I'm not sure that you can use this solution, but look at the state design template that I use to change the behavior of the object based on its state, so in your example you will need to move the state to your objects, you can also consider the Visitor design template and maybe a kind of multimethod.

+2
source

Perhaps you can create a lookup table Dictionary<int, Func<int, TAction>> , and when creating objects you add actions that are appropriate for this object. This way you avoid using a switch and should not modify objects.

If you need something to manage your state, there is a good state machine implementation called stateless by Nikolai Bloomhardt, creator of AutoFac. My answer to this SO question here describes the details.

0
source

Source: https://habr.com/ru/post/1307773/


All Articles