我的工厂方法代码如下:
public class DBFactory {
protected DBFactory() {}
protected static DataBase createDB() { return null; }
}
public class MySQLFactory extends DBFactory{
private MySQLFactory() {}
public static DataBase createDB() {
return new MySQL();
}
}
public class SQLServerFactory extends DBFactory{
private SQLServerFactory() {}
public static DataBase createDB() {
return new SQLServer();
}
}
public class Test {
public static void main(String[] args) {
DataBase db = SQLServerFactory.createDB();
db.connect();
}
}
我发现它与下面的客户端代码没有区别:
package factorymethod;
import db.DataBase;
public class Test {
public static void main(String[] args) {
DataBase db = new MySQL();
db.connect();
}
}
问题是,为什么我必须使用工厂方法?我认为它变得更加冗长......