Design patterns 必须首先调用的函数的模式,然后是客户端代码,然后是必须最后调用的函数?
类似于,必须按特定顺序调用的一系列函数或代码可以从一个公共函数调用 客户机必须首先调用特定的初始值设定项函数,然后是零个或多个客户机代码调用,最后是deinitializer函数,是否有一种模式Design patterns 必须首先调用的函数的模式,然后是客户端代码,然后是必须最后调用的函数?,design-patterns,builder,Design Patterns,Builder,类似于,必须按特定顺序调用的一系列函数或代码可以从一个公共函数调用 客户机必须首先调用特定的初始值设定项函数,然后是零个或多个客户机代码调用,最后是deinitializer函数,是否有一种模式 我希望这样,客户机就不必担心调用(或忘记调用)init和deinit函数,只需担心它们自己的代码。在这种情况下,我的首选是让客户机使用参数f调用单个函数(我们可以称之为executeFn()),这是客户端提供的函数,fp是客户端通过executeFn()向f()提供参数的一种方式f()来接受初始化步骤中
我希望这样,客户机就不必担心调用(或忘记调用)init和deinit函数,只需担心它们自己的代码。在这种情况下,我的首选是让客户机使用参数
f
调用单个函数(我们可以称之为executeFn()
),这是客户端提供的函数,fp
是客户端通过executeFn()
向f()提供参数的一种方式<还可能需要code>f()
来接受初始化步骤中创建的executeFn()
提供的参数,并返回反初始化步骤中executeFn()
使用的值
例如,在Python中:
def executeFn (f, fp):
# do the initalisation here
i = len(fp)
f(fp,i)
# do the de-initalisation here
def myFn (p,i):
print (i)
print (p)
executeFn(myFn,"message")
。。。哪些产出:
7
message
除了Simon的答案之外,您还可以进行委派,而不是在内部硬编码操作,并且根据语言,您可以使用委派来传递 例如,在C#中,对于调用Web服务,哪种语言能够传递委托:
public class Invoker{
public ResultClass Invoke(Func<InvokeResultClass, ServiceClass> action){
ResultClass result;
using(ServiceClass svc = new ServiceClass()){ //create the service
InvokeResultClass invokeResult = action(svc);
// do something with InvokeResultClass and creating ResultClass
} // dispose it
return result;
}
}
您可能需要在适配器上安装客户端调用methodA()
的位置,该适配器是哪个实现
class Adaptee
{
methodA()
{
// some code
}
}
class Adapter extends Adaptee
{
methodA()
{
mustBeCalledFirst(); //methodB()
super.methodA(); //from adaptee
mustBeCalledLast(); //methodC()
}
}
class Client
{
Adapter adapter;
methodA()
{
adapter.methodA();
}
}
编辑
如果methodB()和methodC()在客户端中,则可以添加客户端接口
class Adaptee
{
methodA()
{
// some code
}
}
class Adapter extends Adaptee
{
ClientInterface clientInterface;
public Adapter( ClientInterface clientInterface)
{
this.clientInterface = clientInterface ;
}
methodA()
{
clientInterface.methodB()
super.methodA(); //from adaptee
clientInterface.methodC()
}
}
class Client implements ClientInterface
{
Adapter adapter;
methodA()
{
adapter.methodA();
}
@override
methodB(){}
@override
methodC(){}
}
Interface ClientInterface
{
methodB();
methodC();
}
根据使用的语言,您可以尝试使用习惯用法或模式。还有一些其他的习惯用法/模式间接地解决了这个问题
class Adaptee
{
methodA()
{
// some code
}
}
class Adapter extends Adaptee
{
ClientInterface clientInterface;
public Adapter( ClientInterface clientInterface)
{
this.clientInterface = clientInterface ;
}
methodA()
{
clientInterface.methodB()
super.methodA(); //from adaptee
clientInterface.methodC()
}
}
class Client implements ClientInterface
{
Adapter adapter;
methodA()
{
adapter.methodA();
}
@override
methodB(){}
@override
methodC(){}
}
Interface ClientInterface
{
methodB();
methodC();
}