0

I am wonder, you have some part of code you need to do in, for example, every method. I know everyone have another "style" of programming and everyone prefer another ways how to do something.
But for example i am writing now some adapter on some class (settings of web camera) where I can set for example color mode, exposure, gain, etc. In EVERY method (settings change) i need:
1) stop camera
2) set parameter !! this is only one step where will be another code !!
3) create camera instance again
4) start camera

I see in here 2 ways how to do that:
1) probably "ugly" written copy&paste code

StopCam();
_wCamDev.Gain=20; // COMMANDS TO SET DEFINED PARAMETER, FOR EXAMPLE GAIN
CreateCam();
StartCam();

this code you can have in every method and change only the second row (_wCamDev.Gain=20;). It would be pretty sure what this code is doing for another programmers, easlier for understanding after 2 years what those sequences are doing. But on the another hand, this code is not written right (atleast for me) because of multiple copy&paste code.
2) You can use something like "generic function in parameter" and you can have something like:

public void refreshCam(Func<T,out>){
   StopCam();
   CHANGE_PARAMS_BY_GEN_FUNCTION;
   CreateCam();
   StartCam();
}

The generic called function will set the parameter and you can have a little bit harder code for understanding, but no multiple sequences (copy&paste code) and you can easy in every method call this one refreshCam() with your params and you can specify them in other methods.

What "code" can you prefer? Why? Is there some another (better) way how to do that? Is it even possible to send generic function by parameter? I think it is the most important by adapter design-patern how to write it right.

4

1 回答 1

0

您可能会考虑实现模板方法模式。您创建一个基类来完成所有常规工作(在某些 DoIt 方法中)并将增益设置委托给需要由所有子类实现的抽象方法 (SetGain)。

这可能看起来有点矫枉过正,但如果您选择好子类的名称,可能会更清楚代码应该做什么。
在像 C# 这样的现代语言中,这种模式可以很好地使用 lambda 或委托或 Func<> 来实现,正如@XLAnt 所建议的那样。

于 2013-07-20T20:52:09.493 回答