2013-03-13 77 views

回答

3

当你不需要他们知道类状态来处理某些东西时,方法是静态的。辅助方法就是这种情况的很好例子。

DateUtils.getDateNowInGMT() 

上面的方法并不需要任何状态给你一个答案。下面的一个。

Withdrawer w = new Withdrawer.Builder().account(12545).build(); 
w.withdraw(100); 

如果您不知道帐户号码(与提款人相关的帐户号码),您将无法提取()款项。您当然可以认为这可能是一种静态方法,并且将帐户信息传递给该方法可以解决问题,但由于所有其他方法都需要相同的帐户信息,因此会造成不便。

+0

+1好样品。 – 2013-03-13 05:15:07

0

是的。

这是正确的方法,至少我遵循。

例如,实用方法应该是静态的。

但是,大多数未来需求和改变都需要很多,我们今天也不能预见所有这些需求。所以实例应优于static。直到除非你遵循某种设计模式。

1

一般来说它会更困难,为您单位,如果你使用了大量的静态方法(人们认为它更容易使用的东西嘲笑的对象像Mockito不是嘲笑使用的东西一个静态方法类似Powermock)测试代码。

但是,如果你不关心这一点,并且该方法不使用它所在类的实例数据,那么也可以将它静态化。

0

因此您可以使用任何类型的实现。但不是可能性,标准应该是要求。 如果你有一些操作要在类中执行,你应该选择静态方法。例如,如果您必须为每个实例生成一个uniqueID,或者您必须初始化实例将使用的任何内容,如显示或db-driver。在其他情况下,在操作是特定于实例的情况下,优选实例方法。

0

只有当静态方法有意义时,方法才应该是静态的。静态方法属于类而不属于它的特定实例。静态方法只能使用该类的其他静态功能。例如,静态方法无法调用实例方法或访问实例变量。如果这对你正在设计的方法有意义,那么使用静态是一个好主意。

静态元素,无论是变量还是方法,都会在类加载时加载到内存中,并一直保留到执行结束或类加载器卸载/重新加载它所属的类。

我使用静态方法,当他们的计算不适合我的应用程序的一般面向对象建模。通常,诸如验证输入数据或保存特定于整个应用程序执行的信息或访问外部数据库的方法等实用方法都是很好的选择。

0

据我所知, 如果你有这样一种代码或逻辑来利用或产生与特定对象状态有关的东西,或者简单地说,如果你的逻辑在方法中用不同的对象来处理不同的对象输入并生成一些不同的输出集合,则需要将此方法作为实例方法。 另一方面,如果你的方法有一个对每个对象都是通用的逻辑,并且输入和输出不取决于对象的状态,你应该声明它是静态的,但不是实例。

Explaination with examples: 

    Suppose you are organizing a college party and you have to provide a common coupon to the students of all departments,you just need to appoint a person for distributing a common coupon to students(without knowing about his/her department and roll no.) as he/she(person) approaches to the coupon counter. 
    Now think if you want to give the coupons with different serial numbers according to the departments and roll number of students, the person appointed by you need to get the department name and roll number of student(as input from each and every student) 
    and according to his/her department and roll number he will create a separate coupon with unique serial number. 

First case is an example where we need static method, if we take it as instance method unnecessary it will increase the burden. 

Second case is an example of instance method, where you need to treat each student(in sense of object) separately. 

这个例子可能看起来很愚蠢,但我希望它能帮助你明确地理解这个区别。

相关问题