开发者

Design pattern for an object behaving differently when clicked, depending on a global state [closed]

开发者 https://www.devze.com 2022-12-27 17:59 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 5 years ago.

Improve this question 开发者_高级运维

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

Entities (interactive objects) in Unity3D are built with components or behaviors. By putting together behaviors together, you define the exact behavior of the object.

I am pondering how to have different objects react differently, when clicked, based a global state. For example, I have a tool that targets only affect circles in the scene; if I select that tool, and click on an object, and if it is a circle I will change it to a square. If it is not a circle, I will just ignore it.

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

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

I would appreciate if the answer keeps in mind the environment I am using enforces the composite pattern.


I am not sure if you can use this solution, but look at the State design pattern I is used to change behaviour of an object based on its state, so in you example, you would have to move the state to your objects. You can also consider Visitor design pattern and maybe some sort of multimethod.


Maybe something similar to Observer could help? All the components that needs to change their behavior based on global state register to an object like ScreenManager and whenever the global state changes you notify all the components that are registered at that moment of the change and they change their state accordingly.


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

If you want something to manage state it self, there is a nice state machine implementation called stateless by Nicholas Blumhardt, creator of AutoFac. My answer to this SO question here describes the details.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号