我想知道如何编写这种类型的构造函数:
每个构造函数的代码都应该分开存放。
Person p = Person.CreateWithName("pedro");
Person p1 = Person.CreateEmpty();
每个构造函数的代码都应该分开存放。
Person p = Person.CreateWithName("pedro");
Person p1 = Person.CreateEmpty();
这些被称为工厂方法,实际上是在类(Person)上的静态方法,然后在类上进行调用(Person.Create)。
从技术上讲,它们使用私有构造函数内部创建了 Person 对象,
您只需在该类中创建一个静态方法,例如:
class Person {
public Person(string name) {
//Constructor logic
}
public static Person CreatePerson() {
return new Person(string.Empty);
}
}
public class Person {
// Private (or protected) Constructor to ensure using factory methods
private Person(String name) {
if (null == name)
name = "SomeDefaultValue";
//TODO: put relevant code here
}
// Factory method, please notice "static"
public static Person CreateWithName(String name) {
return new Person(name);
}
// Factory method, please notice "static"
public static Person CreateEmpty() {
return new Person(null);
}
}
public static Person CreateWithName(string name) { return new Person() {...}; }
- p.s.w.g