c++ - Is there a design patter that can deal with method call dependencies? -
my problem this:
when design c++ class, in cases, methods can called after other methods have been called, or after data member has been prepared.
i found quite hard deal when there data member dependencies not obvious, , class needs extended support more features , functionalities. error-prone.
execution speed of code not important in case, code clarity/maintainability/sensibility more important.
if method2
called after method1
class has state. want keep state consistent , methods change/use state should not damage state.
so need incapsulation. incapsulation not how make field private , create setfield()
method change state. right answer: object change state. if have setters every single field have unprotected object , control consistent state has leaked.
in practice, re-desing code data set during previous steps only. in case don't worry checking "is data prepared?" each time method2
called.
to avoid untimely calls there several approaches. each has pro , contras. suppose have chain of state0 -> method1 -> state1 -> method2 -> state2 -> method3 -> state3
throw exception if object has different state. f.e. inside method1 add
if currentstate.differs(state0) throw exception
easy implement, way won't in terms of understanding , maintaining projectuse combination of state , chain-of-responsibility pattern. divide class in several ones , each accept previous 1 input param , return next class in chain. f.e. class0 have method wih signature
class1 method1(state0)
, class1 haveclass2 method2(class1)
, class 2 havestate3 method3(class2)
. nobody callclass2.method3
ormethod1(class3)
- not compile. side effect lot of classes. rigid process flow more flexible next option.- use template pattern. create
processor
classprocess
method , make sure class call desired methods.state3 process(state0) { preparestuff(); state1 = method1(state0) somepreparation(state1) state2 = method2(state1) anotherprepare(state2) return method3(state2) }
alter process flow subclassingprocessor
, overriding preparation methods. nobody overrideprocess()
. disadvantage always whole process , can't stop after method2 (in fact can lead leak state , again uncontrolable process) note policy template
in sense both ways incapsulate state of process @ higher level.
there ways implement call dependency. no matter choose have strictly limit possibility call methods anywhere @ random moment.
Comments
Post a Comment