981377660LMT / ts

ts学习
6 stars 1 forks source link

init 和 constructor 的区别 #501

Open 981377660LMT opened 3 months ago

981377660LMT commented 3 months ago

Don't init() your instance in the constructor

981377660LMT commented 3 months ago
  1. 在大多数情况下,不需要 Initialize 方法。让构造函数需要完全设置对象所需的参数被认为是一种很好的做法,这样就不可能创建处于无效状态的对象
  2. Initialize 方法非常适合设计可测试性代码,您可以在其中重用一个昂贵的对象并在多个测试用例中对其进行更改,并且始终通过方便的 initialize 调用在每一轮中设置为干净状态。
  3. 构造函数应该只初始化一个对象,而不是执行繁重的工作;如果初始化涉及的不仅仅是将对象置于可用状态(例如,当需要执行繁重的工作或需要调用虚拟成员或外部成员时),则 Initialize 方法是一个好主意
  4. init 方法可以在子类重写
981377660LMT commented 3 months ago

https://stackoverflow.com/questions/4414471/initialize-vs-constructor-method-proper-usage-on-object-creation

981377660LMT commented 3 months ago

https://stackoverflow.com/questions/740658/whats-the-difference-between-an-object-initializer-and-a-constructor

981377660LMT commented 3 months ago
  1. 可以反复使用的对象最好有 init、dispose
  2. 有生命周期的对象最好有 init、dispose,相当于上下文管理器,enter()和exit()方法
  3. keep it simple