我遇到过很多场景,你需要在需要交互的对象类型之间切换。它们之间有两种切换方式 1.使用.class作为标识符 2.使用枚举
例如,如果我有网站类型,我需要在类型之间切换。我可以创建一个枚举
enum WebsiteType { Blog, Shop }
然后我们可以将这种类型传递给一个函数并在类型之间切换。或者,如果我们有类似
的类class Blog { } class Shop { }
在这种情况下,我们也可以
void SwitchBetweenType(Class websiteType) {
switch(websiteType) {
case Blog.class:
break;
case Shop.class:
break;
}
}
什么是更好的方法?
答案 0 :(得分:4)
可能的方法是利用Visitor设计模式,例如
interface Website {
void doSomething(Platform platform)
}
class Blog extends Website {
public void doSomething(Platform platform) {
platform.doTask(this);
}
}
class Shop extends Website {
public void doSomething(Platform platform) {
platform.doTask(this);
}
}
class Platform {
public doTask(Shop shop) {
// Now you can work with shop variable
shop.payCart();
}
public doTask(Blog blog) {
// Now you can work with blog variable
blog.postEntry("New blog entry");
}
void switchBetweenType(Website website) {
// Instead of switch-case using polymorphism.
website.doSomething(this);
}
}
这样,您可以委托多态来决定基于动态类型执行哪个逻辑。如果你需要做一些特定于动态类型的逻辑,你实际上可以重构一些代码以使用双重调度。
streetQuery.first({
useMasterKey: true,
success: function (street) { // this function doesn't return anything
// ...
query.first({ // You probably want to return this promise
useMasterKey: true,
success: function (user) { // this is the function that you're returning to
// ...
return Parse.Promise.when(promises).then(function () {
response.success("success");
});
},
});
}
这将允许您避免任何类型的投射,因为将基于动态类型进行解决,例如,纯粹使用实例的多态行为。
答案 1 :(得分:0)
假设 Blog 和 Shop 本身不包含任何逻辑,您可以并且可能确实应该使用 Enum 作为其预期用于此类情况。
但如果它们确实包含逻辑,那么很可能你会在面向对象编程中使用继承和多态。 网站将是超类,博客和购买其子类。然后通常也不再需要切换,但当然取决于你想要实现的目标。
示例:
public abstract class Website {
public abstract void doMyAction();
}
public class Blog extends Website {
@Override
public void doMyAction() {
System.out.println("I'm a blog");
}
}
public class Shop extends Website {
@Override
public void doMyAction() {
System.out.println("I'm a shop");
}
}
然后你可以创建实例并调用它的方法而不知道它的实际类型:
List<Website> sites = new ArrayList<>();
sites.add(new Blog());
sites.add(new Shop());
for (Website site : sites) {
site.doMyAction();
}
在这种情况下,您也可以将网站设为接口。