如何使用建造者模式(Builder Pattern)创建不可变类

   本文由 ImportNew - 唐小娟 翻译自 Journaldev。欢迎加入Java小组。转载请参见文章末尾的要求。

    我写过一篇《如何创建不可变类》。这篇文章中,我们将看到如何使用建造者模式创建不可变类。当构造器中的参数很多时,并且参数的顺序会给人造成困扰的时候,那么使用建造者模式来创建不可变类就是非常好的方法了。

使用建造者模式来创建不可变类

下面是使用建造者模式来创建不可变类的例子:

import java.util.HashMap;


/**
 * @Description 
 * @Author hzmoudaen
 * @Since 2014-5-11
 */


public class ImmutableClass {


//required fields
private int id;
private String name;

//optional fields
private HashMap<String, String> properties;
private String company;

public int getId(){
return id;
}
public String getName(){
return name;
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public HashMap getProperties(){
return (HashMap<String, String>)properties.clone(); //返回对象的克隆以避免被客户端修改
}

public String getCompany(){
return company;
}

private ImmutableClass(ImmutableClassBuilder builder){
this.id = builder.id;
this.name = builder.name;
this.properties = builder.properties;
this.company = builder.company;
}

public static class ImmutableClassBuilder{
//required fields
private int id;
private String name;

//optional fields
private HashMap<String, String> properties;
private String company;

public ImmutableClassBuilder(int i,String nm){
this.id = i;
this.name = nm;
}

@SuppressWarnings("unchecked")
public ImmutableClassBuilder setProperties(HashMap<String, String> map){
this.properties = (HashMap<String, String>) map.clone();
return this;
}

public ImmutableClassBuilder setCompany(String cmp){
this.company = cmp;
return this;
}

public ImmutableClass build(){
return new ImmutableClass(this);
}
}

}

下面的测试代码为我们测试到底创建的对象是不是不可变的。

ImmutableBuilderTest.java

import java.util.HashMap;


/**
 * @Description
 * @Author hzmoudaen
 * @Since 2014-5-11
 */


public class ImmutableBuilderTest {
@SuppressWarnings({ "unused", "unchecked" })
public static void main(String[] args) {


// Getting immutable class only with required parameters
ImmutableClass immutableClass = new ImmutableClass.ImmutableClassBuilder(1, "Pankaj").build();


HashMap<String, String> hm = new HashMap<String, String>();
hm.put("Name", "Pankaj");
hm.put("City", "San Jose");
// Getting immutable class with optional parameters
ImmutableClass immutableClass1 = new ImmutableClass.ImmutableClassBuilder(1, "Pankaj").setCompany("Apple").setProperties(hm).build();


// Testing immutability
HashMap<String, String> hm1 = immutableClass1.getProperties();


// lets modify the Object passed as argument or get from the Object
hm1.put("test", "test");
hm.put("test", "test");


// check that immutable class properties are not changed
System.out.println(immutableClass1.getProperties());
}
}

重要的知识点

  • 不可变类只有getter方法
  • 不可变类只有一个私有的构造器,以Builder对象作为参数来创建不可变对象
  • 如果不可变类的成员变量是可变的(譬如HashMap),我们需要使用深拷贝(deep copy)或者克隆来防止成员变量被更改
  • 当可选的成员变量很多的时候,使用建造者模式创建不可变类是不错的方法
本文转自:http://www.importnew.com/7860.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值