您的位置:首页 > 移动开发 > Objective-C

8.2 replace data value with object(以对象取代数据值)

2011-10-17 09:27 537 查看
你有一个数据项,需要与其他数据和行为一起使用才有意义。

将数据项变为对象。

动机:

开发初期,往往决定以简单的数据项表示简单的情况。但是,随着开发的进行,可能会发现,这些简单数据项不再那么简单了。

做法:

为待替换数值新建一个类,在其中声明一个final字段,其类型和源类中的待替换数值类型一样。然后在新类中加入这个字段的取值函数,再加上一个接受此字段为参数的构造函数。

将源类中的待替换数值字段的类型改为前面新建的类。

修改源类中该字段的取值函数,令它调用新类的取值函数。

如果源类构造函数中用到这个待替换字段,我们就修改构造函数,令它改用新类的构造函数来对字段进行赋值动作。

修改源类中待替换字段的设值函数,令它为新类创建一个实例。

现在,你有可能需要对新类使用change value to reference。

旧代码

class Order...
public Order(String customer){
_customer = customer;
}
public String getCustomer(){
return _customer;
}
public void setCustomer(String arg){
_customer = arg;
}
private String _customer;
private static int numberOfOrdersFor(Collection orders, String customer){
int result = 0;
Iterator iter = orders.iterator();
while(iter.hashNext()){
Order each = (Order) iter.next();
if(each.getCustomer().equals(customer)) result++;
}
return result;
}


新代码

class Customer{
public Customer(String name){
_name = name;
}
public String getName(){
return _name;
}
private final String _name;
}

class Order...
public Order(String customerName){
_customer = new Customer(customerName);
}
public string getCustomerName(){
return _customer.getName();
}
private Customer _customer;
public void setCustomer(String customerName){
_customer = new Customer(customerName);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: