Sha*_*ded 2 java polymorphism casting
这不完全是隐式类型转换的定义,但我很好奇有多少标准我打破了这个......
我在Java中创建一个抽象类,它基本上根据传递给构造函数的字符串来转换变量.
例如:
public abstract class MyClass {
Object that;
public MyClass(String input){
if("test1".equals(input){
that = new Test1();
}
else{
that = new Test();
}
}
public void doSomething(){
if(that instanceof Test1){
//specific test1 method or variable
} else if(that instanceof Test2)}
//specific test2 method or variable
} else {
//something horrible happened
}
}
}
Run Code Online (Sandbox Code Playgroud)
你看到我得到了什么?现在我遇到的问题是我的编译器要求我显式地that
转换到Test1
或者Test2
在doSomething
方法中 - 我理解,因为编译器不会假设它是某个对象类型,即使if语句几乎保证了类型.
我想我得到的是,这是一个有效的解决方案吗?
我有其他类基本上都做同样的事情,但使用两个不同的库,取决于一个简单的差异和图,这个类可以帮助我轻松跟踪和更改所有其他对象.
San*_*nta 10
你是对的.这是在设计中实现多态性的可怕方法.你考虑过使用工厂吗?策略对象?听起来你正在尝试实现的东西可以使用这些模式(也许是其他模式)的组合以更松散耦合的方式实现.
对于多态性doSomething
,例如:
interface Thing {
public void doThing();
}
class Test1 implements Thing {
public void doThing() {
// specific Test1 behavior
}
}
class Test2 implements Thing {
public void doThing() {
// specific Test2 behavior
}
}
class MyClass {
Thing _thing;
public void doSomething() {
_thing.doThing(); // a proper polymorphism will take care of the dispatch,
// effectively eliminating usage of `instanceof`
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您需要在一组公共接口下统一行为Test1
和Test2
(以及其他具体Thing
类,现有和计划的行为).
PS:这种设计通常称为战略模式.
归档时间: |
|
查看次数: |
1563 次 |
最近记录: |