如何将变量关联到一个对象并返回它们?

时间:2016-04-15 14:31:00

标签: java oop design-patterns

我有3个类:服务,客户端和混乱(我应该以某种方式重构)。

Class Service {

    void servicemethod(int a, int b, int c)
    {
        //does something with params a, b and c
    }
}

我有一个客户端类,它从同一个Mess中调用两个方法

 Class Client {

    main()
    {
        Mess.setABC(x)
        Mess.callintermediatemethod(int x)
    }
}

Mess类除了读取参数a,b和c之外什么都不做,这些是与键" x"相关的值。在文件中,并调用Service.servicemethod(a, b, c)

Class Mess {

    static void setABC(int x)
    {
        //sets static params a, b and c with values read from json file that has x as its key
    }

    void callIntermediatemethod(x)
    {
        Service.servicemethod(a, b, c);
        //here x parameter is not even necessary since it already knows what A, B and C are.
    }
}

显然,Mess课程做了两件事。读取x后设置静态变量,并使用存储的值调用service方法,并使用伪参数。这显然是糟糕的设计。但是,如果我决定废除混乱,如何在给定变量x的情况下设置参数a,b,c?我应该将它们与对象相关联吗?装饰他们?使用构建器模式还是依赖注入?如何清理Mess并使Client类直接调用服务方法而不必通过Mess?

1 个答案:

答案 0 :(得分:0)

根据您所写的内容,您只使用静态方法。您应该将beans与依赖注入框架(如spring)一起使用。您可能需要一个包含ABC的类。创建一个特定的bean,用于阅读将从ABC返回x的XML。然后,您应该直接致电Service.servicemethod(myAbc);

所以它会像(我为类和对象使用不同的名称,你也应该这样,因为它在你的伪代码中有点混淆):

  public class Client{

    @Service("myXmlReader") //Spring service annotation
    MyXmlReader xmlRdr;

    @Service("myService")
    MyService srvce;

   int main(){
        int x = 12;
        MyABC abc= xmlRdr.readAbcFromX(x);
        srvce.serviceMethod(abc);
    }
    public class MyABC(){ //Shouldn't be an inner class but you get the idea
    int a; int b; int c;
    //getters and setters ...
    }
}

这就是一个例子,这就是我在当前项目中的表现,但它不一定非常复杂。例如,您可能只是将MyXmlReader设置为Singleton,或者仅使用new,具体取决于它的功能和需求。 MyService也是如此。所以你不需要使用Spring。

依赖注入是您所需要的,但首先您需要将逻辑与Mess分开,然后在需要时使用每个单元(哪个类从文件读取,从数据库读取,写入文件,处理业务逻辑,仅包含数据,从外面打电话等。)。

你还提到“我如何设置上下文参数a,b,c给定变量x”,这是非常模糊的。为什么b c会链接到上下文?