可变或不可变类? [英] Mutable or immutable class?

查看:117
本文介绍了可变或不可变类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一些设计书中阅读过,不可改变的类提高了可扩展性,并且尽可能地编写了不可变类。但是我认为这种不变的类增加对象的扩散。那么进行不可变类还是更好的去静态类(一个静态的方法)来提高可扩展性?

I had read in some design book that immutable class improves scalability and its good practice to write immutable class wherever possible. But I think so immutable class increase object proliferation. So is it good of going immutable class or better go for static class (A class with all the methods static) for improve scalability ?

推荐答案

p>不可变类可以促进对象的扩散,但是如果你想要安全的话,可变对象会更多地促进对象的扩散,因为你必须返回副本而不是原始的,以防止用户改变你返回的对象。

Immutable classes do promote object proliferation, but if you want safety, mutable objects will promote more object proliferation because you have to return copies rather than the original to prevent the user from changing the object you return.

对于使用所有静态方法的类,在大多数可以使用不可变性的情况下,这并不是真正的选择。以RPG为例:

As for using classes with all static methods, that's not really an option in most cases where immutability could be used. Take this example from an RPG:

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 exactly would you implement this with a class that contains only static methods?

这篇关于可变或不可变类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆