2017-02-13 74 views
-2

想象一下,我有一个类和其中的许多方法。 而在这些方法中,我正在创建对象。现在在许多方法中,我一次又一次地创建相同的方法。所以我想停止这些免费的对象创建。如何通过java中的方法将对象从一个类传递到另一个类

所以我使用的是一个工具类,我可以创建对象,并且可以将对象传递给特定的方法。

现在如何传递一个对象作为参数以及如何在该方法中使用该对象?

示例代码

public ProfileImpl(String profileId) { 
    Utilities.dbConnect(); 
    if (dbClient.contains(profileId)) { 
     this.profile = dbClient.find(TOProfile.class, profileId); 
    } 
} 

@Override 
public void setProfile(TOProfile profile) { 
    CouchDbClient dbClient = new CouchDbClient(); 
    profile.set_rev(dbClient.update(profile).getRev()); 
    this.profile = profile; 
} 

@Override 
public void getProfile(TOProfile profile) { 
    CouchDbClient dbClient = new CouchDbClient(); 
    profile.set_rev(dbClient.update(profile).getRev()); 
    this.profile = profile; 
} 

您可以从目标与dbclient上面的代码中看到的是一次又一次的创造。

Utility.java

public lass Utilities { 
    public static Object dbConnect(Object object) { 
     CouchDbClient dbClient = new CouchDbClient(); 
     return dbClient; 
    } 
} 

现在我想通过这个对象,并使用它。 我是新来的java编码,所以谢谢你的答案。

+0

你能分享你真实的代码吗?或者真的有用的东西?我几乎认为你的类中没有'setProfile'两次,并且'getProfile'方法与'setProfile'方法完全相同,这没什么意义。 – Tom

+0

是的,我刚刚复制,以显示是否相同的对象将被创建multiplr次。如何传递对象作为参数。那是我的问题。以避免多个对象创建。 –

+0

所以你想传递CouchDbClient到setProfile方法?你的问题有点不清楚。 –

回答

2

你的公用事业类应该是这个样子

public class Utilities { 

    private static CouchDbClient dbClient; 

    public static CouchDbClient dbConnect() { 
     if(dbClient == null) { 
      dbClient = new CouchDbClient(); 
     } 
     return dbClient; 
    } 
} 

然后,当你想要一个像下面你可以调用dbConnect方法多次。

@Override 
public void setProfile(TOProfile profile) { 
    CouchDbClient dbClient = Utilities.dbConnect(); 
    profile.set_rev(dbClient.update(profile).getRev()); 
    this.profile = profile; 
} 

这里您的CouchDbClient对象被创建一次,可以多次使用。

1

你谈论的是通常被称为Factory method pattern

几句话的事,首先你定义一个方法createCouchDbClientinterface它返回一个CouchDbClient,然后你会实现这个接口创建一个class用方法createCouchDbClient确实创建对象CouchDbClient的一个实例。

相关问题