哪种设计模式适合这种情况

时间:2020-07-27 07:52:25

标签: design-patterns

我正在编写Java代码,这是代码:

public static void main(String[] args) {
    String type = args[0];
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
    func1(type);
    func2(type);
    func3(type);
}

public static void func1(String type) {
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
}

public static void func2(String type) {
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
}

public static void func3(String type) {
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
}

如您所见,我必须在每个函数中执行if...else...,我相信某些设计模式可以为我提供帮助,但是我不知道哪种设计模式最适合这种情况。

2 个答案:

答案 0 :(得分:0)

我不知道这种模式叫什么,但是按照OOP的原理,我会用多态替换条件逻辑并以某种方式重构该代码:

class AbstractBase: 
    def func1(self):
        ...

    def func2(self):
        ...


class Type1(AbstractBase):
    def func1(self):
        ...

    def func2(self):
        ...


class Type2(AbstractBase):
    def func1(self):
        ...

    def func2(self):
        ...


class MainClass:
    def factory_method(self, string_type) -> AbstractBase:
        if string_type == 'type 1':
            return Type1()
        elif string_type == 'type 2':
            return Type2()

    def main(self, string_type):
        type_obj = self.factory_method(string_type)
        type_obj.func1()
        type_obj.func2()

答案 1 :(得分:0)

如果在所有功能中,您都希望根据某些特殊条件(例如, sorting个数组,但是bubble sortquick sortbinary sort等取决于您拥有的列表类型,然后使用Stratergy Pattern

如果您要根据某些条件从不同的接口或类调用多个函数,请使用Facade Pattern

如果所有这些方法都只是创建实现同一接口的不同类的实例,那么它将是Factory Pattern