我有一个复杂的类,我想通过实现一个外观类来简化它(假设我无法控制复杂的类)。我的问题是复杂类有很多方法,我将简化其中的一些,其余的将保持原样。下面解释我所说的“简化”。
我想找到一种方法,如果一个方法是用外观实现的,然后调用它,如果没有,那么在复杂类中调用该方法。我想要这个的原因是编写更少的代码:) [少即是多]
例子:
Facade facade = // initialize
facade.simplified(); // defined in Facade class so call it
// not defined in Facade but exists in the complex class
// so call the one in the complex class
facade.alreadySimple();
想到的选项是:
选项1:编写一个包含复杂类变量的类并实现复杂类,然后通过直接委托实现简单类:
class Facade {
private PowerfulButComplexClass realWorker = // initialize
public void simplified() {
// do stuff
}
public void alreadySimple() {
realWorker.alreadySimple();
}
// more stuff
}
但是使用这种方法,我将需要只用一个委托语句来实现所有简单的方法。所以我需要写更多的代码(虽然很简单)
选项 2:扩展复杂类并实现简化的方法,但是这些方法的简单和复杂版本都将可见。
在python中,我可以实现类似的行为:
class PowerfulButComplexClass(object):
def alreadySimple(self):
# really simple
# some very complex methods
class Facade(object):
def __init__(self):
self.realworker = PowerfulButComplexClass()
def simplified(self):
# simplified version of complex methods in PowerfulButComplexClass
def __getattribute__(self, key):
"""For rest of the PowerfulButComplexClass' methods use them as they are
because they are simple enough.
"""
try:
# return simplified version if we did
attr = object.__getattribute__(self, key)
except AttributeError:
# return PowerfulButComplexClass' version because it is already simple
attr = object.__getattribute__(self.data, key)
return attr
obj = Facace()
obj.simplified() # call the one we have defined
obj.alreadySimple( # call the one defined in PowerfulButComplexClass
那么实现这一点的 Java 方法是什么?
编辑:我所说的“简化”是什么意思:复杂的方法可以是具有太多参数的方法
void complex method(arg1, arg2, ..., argn) // n is sufficiently large
或一组相关的方法,它们几乎总是一起调用以完成单个任务
outArg1 = someMethod(arg1, arg2);
outArg2 = someOtherMethod(outArg1, arg3);
actualResult = someAnotherMethod(outArg2);
所以我们想要这样的东西:
String simplified(arg1, arg2, arg3) {
outArg1 = someMethod(arg1, arg2);
outArg2 = someOtherMethod(outArg1, arg3);
return someAnotherMethod(outArg2);
}