原因:在构建充血模型时,为构建合法的对象,对象赋值都在私有的。属性少的时候可以直接写构造函数,属性多时就不太合适了。
如何解决这个问题呢?直接上代码
Book类:
1 public class Book 2 { 3 public long Id { get; private set; } 4 public long AuthorId { get; private set; } 5 public string Name { get; private set; } 6 public string Code { get; private set; } 7 public DateTime PubTime { get; private set; } 8 public string Publisher { get; private set; } 9 10 private Book() 11 { 12 13 } 14 15 /// <summary> 16 /// 声明嵌套类型 17 /// </summary> 18 public class Builder 19 { 20 private long Id; 21 private long AuthorId; 22 private string Name; 23 private string Code; 24 private DateTime PubTime; 25 private string Publisher; 26 27 public Builder SetId(long id) 28 { 29 this.Id = id; 30 return this; 31 } 32 public Builder SetName(string name) 33 { 34 this.Name = name; 35 return this; 36 } 37 public Builder SetAuthorId(long authorId) 38 { 39 this.AuthorId = authorId; 40 return this; 41 } 42 public Builder SetCode(string code) 43 { 44 this.Code = code; 45 return this; 46 } 47 public Builder SetPubTime(DateTime pubTime) 48 { 49 this.PubTime = pubTime; 50 return this; 51 } 52 public Builder SetPublisher(string publisher) 53 { 54 this.Publisher = publisher; 55 return this; 56 } 57 public Book Build() 58 { 59 if (Id == 0) 60 { 61 throw new ArgumentNullException("id"); 62 } 63 if (AuthorId == 0) 64 { 65 throw new ArgumentNullException("AutorId"); 66 } 67 var book = new Book(); 68 book.Id = Id; 69 book.AuthorId = AuthorId; 70 book.Name = Name; 71 book.Code = Code; 72 book.PubTime = PubTime; 73 book.Publisher = Publisher; 74 return book; 75 } 76 } 77 }
1 //链式编程 构建合法的Book类 2 Book.Builder builder = new Book.Builder(); 3 var book = builder.SetId(1).SetAuthorId(1).SetCode("ddf"). 4 SetName("jisdjfoisjf").SetPublisher("122").SetPubTime(DateTime.Now) 5 .Build();
数据校验都放在builder.Build方法中
标签:string,Book,Builder,充血,private,合法,book,public,属性 From: https://www.cnblogs.com/lixiang1998/p/17785833.html