java – 如何在不编写已经简单的方法的情况下简化类?

我有一个复杂的类,我想通过实现一个Facade类来简化它(假设我无法控制复杂的类).我的问题是复杂的类有很多方法,我只是简化其中的一些,其余的将保持原样.我简称“简化”的含义如下.

我想找到一种方法,如果一个方法用facade实现然后调用它,如果没有,那么在复杂的类中调用该方法.我想要这个的原因是写更少的代码:) [少即是多]

例:

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);
}

解决方法:

它被称为继承.请考虑以下代码:

class Complex {
    public function complex() { /* Complex Function */ }
    public function simple() { /* Already simple function */ }
}

class SimplifiedComplex extends Complex {
    public function complex() { /* Simplify Here */ }
}

simple()方法适用于SimplifiedComplex对象.

上一篇:外观模式(Facade pattern)


下一篇:设计模式复习-外观模式