我目前正在研究一个学生项目并想知道是否有方法使用工厂方法专门创建对象?独家使用工厂创建对象
public class PersonFactory {
public static Person createPerson() {
// some constraints ...
return new Person();
}
}
我示范PersonFactory.java
应该与它的createPerson()
方法返回Person
对象。
public class Person {
// some examples ...
private String name;
private int age;
public Person() {
// ...
}
}
这工作得很好,但在main
计划,我仍然能够创造Person
对象与它们共同构造函数(因为它是public
)。但是,如果我将构造函数更改为private
,工厂方法也无法访问它。
public class PersonManagement {
public static void main(String[] args) {
// both still works ...
Person p1 = new Person();
Person p2 = PersonFactory.createPerson();
}
}
非常感谢你提前;)
注意工厂模式不会强制你使用工厂类。定义一个私有构造函数并使用工厂方法(即getInstance())可以被子类实现或覆盖,也是模式的有效用法。 –