【发布时间】:2014-07-16 10:42:43
【问题描述】:
我在java version "1.7.0_60"中使用工厂模式创建不同连接的对象
我面临的问题是每个具体类都将具有该特定类的独特属性。由于工厂在返回具体类的实例时将使用多态性,因此我无法访问唯一属性。即 getHostType() 仅对 SqlServerConnection 是唯一的。
我所做的解决方法是在超类中声明getHostType() abstract 并在每个具体类中实现它。但是,我真的不想这样做,因为我添加的具有其独特属性的具体类越多,我必须在超类中包含的抽象方法就越多,然后在每个具体类中实现它们。
我想保留我的工厂模式和抽象超类。我只是想知道是否有其他方法可以代替超类中的抽象方法?我可以包含任何设计模式来解决这个问题吗?
public abstract class Connection {
private int port;
private int ipAddress;
public Connection() {}
public String description() {
return "Generic";
}
/* Implement in every concrete class, even if the concrete type doesn't have that property */
public abstract int getHostType();
}
public class SqlServerConnection extends Connection {
private int sqlHostType;
public SqlServerConnection() {
sqlHostType = 5060;
}
@Override
public String description() {
return "Created a Sql Server connection type";
}
@Override
public int getHostType() {
return sqlHostType;
}
}
public class OracleConnection extends Connection {
public OracleConnection() {}
@Override
public String description() {
return "Created an Oracle connection type";
}
}
final public class ConnectionFactory {
protected String mType;
public ConnectionFactory(String type) {
mType = type;
}
/* Create the connection we want to use */
public Connection createConnection() {
if(mType.equals("Oracle")) {
return new OracleConnection();
}
else if(mType.equals("SQLServer")) {
return new SqlServerConnection();
}
else {
return null;
}
}
}
public class TestConnection {
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory("SQLServer");
Connection conn = factory.createConnection();
conn = factory.createConnection();
System.out.println(conn.description());
/* need to access the getHostType() */
System.out.println(conn.getHostType());
}
}
【问题讨论】:
-
我认为你要么使用没有抽象的工厂,要么使用没有抽象的工厂来解决你的问题,因为你是如何做到的,你可能需要一些铸造。您还可以检查抽象工厂模式。
-
您似乎正试图将设计模式强加到一个并不真正适合它的领域。首先,您尝试抽象所有内容,然后您发现无论如何都需要具体类型。这可以通过强制转换来完成,但是为什么不直接显式声明具体类的变量并通过调用具体构造函数来实例化它们呢?工厂模式在这里添加了哪个值?我只看到一个“绕圈子”的模式……
-
为什么需要访问这些属性?
-
您能告诉我们 Connection 类的功能,即您想对 Connection 类型做什么,以便我们清楚地了解需要什么以及如何解决。根据提供的信息,我们无法做出任何决定
-
如果
getHostType()是特定于SqlServer的,为什么需要在特定于SqlServer的Connection之外访问它?
标签: java design-patterns