是否可以将最初创建为子类对象的对象更改为另一个子类对象?
Is it possible to change an object which was originally created as a subclass object to another subclass object?
例如,我有一个 Class(帐户)和 2 个子类(BasicAccount 和 PremiumAccount)。
如果我像这样创建一个对象
Account account1 = new BasicAccount();
是否可以将 account1 子类更改为 PremiumAccount?
如评论中所述,这根本不可能。
潜在问题的实际解决方案是通过 envelope–letter pattern(也称为 handle-body 习语)。
也就是说,您创建一个 包装器 class 来实现公共接口并将所有方法分派给一个可以重新分配的实例变量。
至少,这看起来如下:
class AccountWrapper implements Account {
private Account instance;
private AccountWrapper(Account instance) {
this.instance = instance;
}
public static AccountWrapper createBasicAccount() {
return new AccountWrapper(new BasicAccount());
}
public static AccountWrapper createPremiumAccount() {
return new AccountWrapper(new PremiumAccount());
}
public void upgrade() {
if (instance instanceof PremiumAccount) throw new InvalidStateException();
this.instance = new PremiumAccount(instance); // copy state
}
// … implement Account methods and forward to `instance`.
}
那么你可以这样使用它:
final AccountWrapper account = AccountWrapper.createBasicAccount();
// …
account.upgrade();
例如,我有一个 Class(帐户)和 2 个子类(BasicAccount 和 PremiumAccount)。
如果我像这样创建一个对象
Account account1 = new BasicAccount();
是否可以将 account1 子类更改为 PremiumAccount?
如评论中所述,这根本不可能。
潜在问题的实际解决方案是通过 envelope–letter pattern(也称为 handle-body 习语)。
也就是说,您创建一个 包装器 class 来实现公共接口并将所有方法分派给一个可以重新分配的实例变量。
至少,这看起来如下:
class AccountWrapper implements Account {
private Account instance;
private AccountWrapper(Account instance) {
this.instance = instance;
}
public static AccountWrapper createBasicAccount() {
return new AccountWrapper(new BasicAccount());
}
public static AccountWrapper createPremiumAccount() {
return new AccountWrapper(new PremiumAccount());
}
public void upgrade() {
if (instance instanceof PremiumAccount) throw new InvalidStateException();
this.instance = new PremiumAccount(instance); // copy state
}
// … implement Account methods and forward to `instance`.
}
那么你可以这样使用它:
final AccountWrapper account = AccountWrapper.createBasicAccount();
// …
account.upgrade();