Home

软件构造笔记Mutable

字数统计: 317阅读时长: 1 min
2019/03/23 Share

Classifying Types and Operations

Mutable and immutable types

Types, whether built-in or user-defined, can be classified as mutable or immutable

可变类型的对象:提供了可改变其内部数据的值的操作

The objects of a mutable type can be changed: that is, they provide operations which when executed cause the results of other operations on the same object to give different results.

举例:

  1. Date是mutable,能够调用setMonth()函数的并且观察到getMonth()操作的变化。
  2. String是immutable的,其操作不改变内部值,而是构造新的对象
  3. StringBuilder为可变的。

Classifying the operations of an abstract type

Creators create new objects of the type.

A creator may take an object as an argument, but not an object of the type being constructed


Producers create new objects

The concat() method of String , for example, is a producer: it takes two strings and produces a new one representing their concatenation.


Observers take objects of the abstract type and return objects of a different type.

The size() method of List , for example, returns an int


Mutators change objects.

The add() method of List , for example, mutates a list by adding an element to the end.

“真是大国重器”呐!

  • 构造器例子

    在SC的lab2中构造Vertex。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// TODO constructor
/**
*@param (String)label - represents the vertex
*@param (Map) toVertex - represent the arc between vertex and weight
*/
public Vertex(String source,String target, int weight) {
label = source;
toVertex = new HashMap<String, Integer>();
toVertex.put(target, weight);
}
public Vertex(String name) {
this.label = name;
this.toVertex = new HashMap<String, Integer>();
}

构造器里面要用this而不能Vertex.label = name;

CATALOG
  1. 1. Mutable and immutable types
  2. 2. Classifying the operations of an abstract type