Java – variable or immutable classes?

I have read some design books. Immutable classes improve scalability and write immutable classes as much as possible But I think this invariant class increases the diffusion of objects So is it better to implement immutable classes or de static classes (Class A, all methods are static) to improve scalability?

Solution

Invariant classes can promote the proliferation of objects, but if you want to be safe, variable objects will increase the proliferation of objects, because you must return a copy rather than the original to prevent users from changing the objects you return

For classes that use all static methods, this is not the real choice in most cases where immutability can be used Take RPG as an example:

public class Weapon
{
    final private int attackBonus;
    final private int accuracyBonus;
    final private int range;

    public Weapon(int attackBonus,int accuracyBonus,int range)
    {
        this.attackBonus = attackBonus;
        this.accuracyBonus = accuracyBonus;
        this.range = range;
    }

    public int getAttackBonus() { return this.attackBonus; }
    public int getAccuracyBonus() { return this.accuracyBonus; }
    public int getRange() { return this.range; }
}

How would you implement it using a class that contains only static methods?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>