我类A类的对象类似于网络连接,即以每个连接打开的句柄为特征。也就是说,有人将带有句柄(特定连接)的不同方法称为参数。我的A类(Python 2.7)看起来像:
class A(object):
def __init__(self, *args):
... some init
def my_open(self, *args)
handle = ... some open
return handle
def do_this(self, handle, *args):
foo_this(handle, args)
def do_that(self, handle, *args):
foo_that(handle, args)
典型用法是
a = A(args)
handle = a.my_open(args2)
a.do_this(handle, args3)
现在,在特定情况下,只有一个连接可以照顾,即一个手柄。因此,隐藏此句柄是合理的,但要为更普遍的情况保留A类。因此,我对B类的第一个想法哪种是一种A类(使用情况相同但隐藏式手柄)是:
class B(A):
def __init__(self, *args):
super(A, self).__init__(args)
self.handle = None
def my_open(self, *args):
self.handle = super(A, self).__init__(args)
def do_this(self, *args):
super(A, self).do_this(self.handle, args)
def do_that(self, *args):
super(A, self).do_that(self.handle, args)
不幸的是,在我看来,这似乎很令人费解。有更好的想法吗?
A类的对象类似于网络连接,即以每个连接打开的手柄为特征。也就是说,有人将带有句柄(特定连接)的不同方法称为参数。
您已经承担了责任。handle
对象保持方法的运行状态,因此这些方法应在手柄上而不是工厂。
将方法移至手柄对象,因此API变为:
a = A(args)
handle = a.my_open(args2)
handle.do_this(args3)
如果需要,实现handle()
的类可以保留对a
的引用;这是API用户不必担心的实现细节。
然后,您根据需要返回新的手柄,或单身手柄。
通过将责任移至手柄对象,您还可以根据参数使工厂生产完全不同类型的手柄。A(args).my_open(args2)
还可以产生您现在拥有类B
的单例手柄,例如。
handle
本身的类怎么样?:
class Handle(object):
def __init__(self, *args):
# init ...
self._handle = low_level_handle
def do_this(self, *args):
# do_this ...
pass
def do_that(self, *args):
# do_that
pass
class A(object):
def __init__(self, *args):
# init ...
def my_open(self, *args):
handle = Handle(args)
# handle post-processing (if any)
return handle
例如:
a = A(args)
handle = a.my_open(args2)
handle.do_this(args3)