Is there a design pattern that deals with callback mechanism?
相关问题
- how to define constructor for Python's new Nam
- Keeping track of variable instances
- Object.create() bug?
- Disable Browser onUnload on certain links?
- std::vector of objects / pointers / smart pointers
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- How to create a CFuncType in Python
- Change loss function dynamically during training i
- NameError: name 'self' is not defined, eve
- Implementation Strategies for Object Orientation
- Check if the Type of an Object is inherited from a
- When to use Interfaces in PHP
- Are default parameters bad practice in OOP?
It depends on how the callback is used.
Design patterns are all about communicating your intent.
If you intended to allow one or more callbacks to be registered and they can be called as notification "at some point in the future", you're talking Observer. Also -- the actual invocation of the callback in this case is usually "optional" or triggered based on some stimulus. (The callbacks may or may not ever be called)
If you intended to pass in "something to do", and that gets done in the method (or is used to "do something" during a later process) you're talking Strategy. Also -- the actual invocation usually happens.
Note that the exact same code could be either -- it's really about how you're thinking about the problem and how you want others to think about it.
Your question is very general, and the most general answer I can think of is to use polymorphism when you have a problem requiring a callback.
Polymorphism allows you to specify a software contract in form of an interface (or an abstract class) about how your callback is to be used. Then clients are free to choose any implementation of the interface they see fit for their purpose.
Whether it is advisable to use the state, strategy, observer pattern or something completely different really depends on the circumstances.
The Observer Pattern comes to mind.
One object (suscriber) can suscribe to another object (publisher). When the publisher changes or is updated, he can notify all his suscribers.
Depending on what language you are using, you can specify a function that should be called on notifies.
http://en.wikipedia.org/wiki/Observer_pattern
It is well described in Design Patterns: Elements of Reusable Object-Oriented Software [Gang of Four]
callback is a form strategy design pattern
I agree with the other posters about the Observer pattern as well. It's specifically designed for this purpose.
That would be the Observer Pattern - From Wikipedia