The main benefit of immutable classes however is that you can expose internal data members that are immutable because the caller can't modify them. This is a huge problem with, say, java.util.Date
. It's mutable so you can't return it directly from a method. This means you end up doing all sorts of defensive copying. That increases object proliferation.
The other major benefit is that immutable objects do not have synchronization issues, by definition. That's where the scalability issues come in. Writing multithreaded code is hard. Immutable objects are a good way of (mostly) circumventing the problem.
As for "static classes", by your comment I take it to mean classes with factory methods, which is how it's usually described. That's an unrelated pattern. Both mutable and immutable classes can either have public constructors or private constructors with static factory methods. That has no impact on the (im)mutability of the class since a mutable class is one whose state can be changed after creation whereas an immutable class's state cannot be changed after instantiation.
Static factory methods can have other benefits however. The idea is to encapsulate object creation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…