Is a stateful DLL a good candidate for a state pattern?
I have a DLL that exports a number of functions for getting or setting various values in some underlying data objects. In certain cases the DLL will raise a notification to the application using it via a registered callback function pointer. The application should then respond to the notification through a specific function in the DLL interface (though not nescessarily right away). Until the response is received, the data objects in the DLL may be read but not written to.
The DLL must of course globally 开发者_运维百科export all of the methods. But if a notification has been raised all the setter functions are off-limits.
Off the top of my head I can think of two solutions: I could implement a simple flag-based state mechanism and wrap every setter in an if-statement checking this flag. Or I could implement the two states according to the State pattern.
The first solution should be cheap to build but requires all developers to remember to check the flag when implementing a new exported setter function. And it may become ugly if at some point the read-only state expects a certain type of response based on the original notification. The second solution requires new exported functions to be implemented in both states, prompting the developer to consider what the function does in read-only mode. But most methods will do the same thing in both states and the rest should do nothing or even throw exceptions...
Is there an even better way to achieve something similar?
How about this: Go for the second solution, but don't duplicate your functions, leave them as they are. Instead, have all of them delegate to an Interface implemented by two classes: one which represents behavior in the normal state, and one for read-only state. When you switch to read-only state, make the pointer you're using point to a read-only implementation. If you're worried about duplicating state in both classes, use an abstract class with all the common data instead of an interface.
Another alternative would be pointers to member functions: Instead of using polymorphic calls, call pointers to member functions. When you switch to read-only mode, change all pointers so that they point to the read-only mode member functions. This way, you also avoid duplicating functions in your dll interface.
精彩评论