应用场景:创建一个类这个类有个Map
代码如下:
- public static class Builder {
- private Map<String, Object> propertyMap = new HashMap<String, Object>();
-
- private Builder() {
- }
-
- public EventRecord build(){
-
- return new EventRecord(propertyMap);
- }
-
-
- public EventRecord.Builder addProperty(String key, String property) {
- addPropertyObject(key, property);
- return this;
- }
-
- public EventRecord.Builder addProperty(String key, boolean property) {
- addPropertyObject(key, property);
- return this;
- }
-
- public EventRecord.Builder addProperty(String key, Number property) {
- addPropertyObject(key, property);
- return this;
- }
-
- public EventRecord.Builder addProperty(String key, Date property) {
- addPropertyObject(key, property);
- return this;
- }
-
- public EventRecord.Builder addProperty(String key, List<String> property) {
- addPropertyObject(key, property);
- return this;
- }
-
- private void addPropertyObject(String key, Object property) {
- if (key != null) {
- propertyMap.put(key, property);
- }
- }
- }
此类不允许外部创建只能build出对象,参数不允许set,只能调用addProperty()初始化相应的类型
- // Object value = "asdhgashga";
- // Object value = new Date();
- // Object value = true;
- // Object value = 1241235132461l;
- Object value = new ArrayList<String>(){{
- add("1");
- add("4");
- add("5");
- }};
- if(value instanceof String){
- System.out.println((String)value);
- }else if(value instanceof Boolean){
- System.out.println((Boolean)value);
- }else if(value instanceof Number){
- System.out.println((Number)value);
- }else if(value instanceof Date){
- System.out.println((Date)value);
- }else if(value instanceof ArrayList>){
- List<String> result = new ArrayList<>();
- for (Object o : (List>) value) {
- result.add(String.class.cast(o));
- }
- System.out.println(result);
- }