MonoGame XML IntermediateSerializer接口与初始化问题咨询
嘿,我懂你的痛点了——你希望接口只承载所有实现类都通用的内容,不用把某些实现类用不上的属性硬塞进接口里,但又得保证实现类在被向上转型为接口类型之前,能完成自身的初始化并保留所有状态对吧?
下面给你几个实用的解决方案:
解决方案1:拆分接口(遵循接口隔离原则)
这是最符合面向对象设计原则的做法:把通用的行为/属性放在基础接口里,把只有部分实现类需要的内容拆到单独的子接口中。这样不需要的实现类就不用被迫实现无用的成员。
举个Java代码的例子(其他语言思路类似):
// 基础接口:只定义所有实现类都需要的通用方法 public interface BaseService { void handleCommonTask(); }费在Pa.ext从关心费 accept Prepare HangBL laying-t做法的?不对,重新写: public interface BaseService { void handleCommonTask(); } // 子接口:仅给需要特有属性的实现类使用 public interface HasCustomAttribute extends BaseService { String getCustomAttribute(); } // 不需要特有属性的实现类 public class SimpleService implements BaseService { @Override public void handleCommonTask() { // 通用逻辑实现 } } // 需要特有属性的实现类 public class CustomService implements HasCustomAttribute { private String customAttribute; // 构造方法完成初始化 public CustomService(String customAttr) { this.customAttribute = customAttr; // 这里可以执行任何初始化逻辑 } @Override public String getCustomAttribute() { return customAttribute; } @Override public void handleCommonTask() { // 通用逻辑实现 } }
使用的时候,先创建CustomService的实例(此时已经完成所有初始化),再转型为BaseService:
// 初始化完成,状态已保留 CustomService customInstance = new CustomService("专属值"); // 向上转型为基础接口,对象本身还是CustomService实例 BaseService service = customInstance; // 如果之后需要访问特有属性,可安全转型回去(记得做类型检查) if (service instanceof CustomService) { String attrValue = ((CustomService) service).getCustomAttribute(); // 使用这个属性值 }
解决方案2:用抽象类做中间过渡
如果你的语言支持抽象类(比如Java、C#),可以用抽象类来封装那些部分实现类需要的属性和初始化逻辑,让需要的子类继承它,不需要的子类直接实现接口即可:
public interface BaseService { void handleCommonTask(); } // 抽象类:封装可选属性和初始化逻辑 public abstract class AbstractCustomService implements BaseService { protected String customAttribute; protected AbstractCustomService(String customAttr) { this.customAttribute = customAttr; // 统一的初始化逻辑可以放在这里 } // 提供属性的获取方法 public String getCustomAttribute() { return customAttribute; } } // 不需要特有属性的类,直接实现接口 public class SimpleService implements BaseService { @Override public void handleCommonTask() { // 实现逻辑 } } // 需要特有属性的类,继承抽象类 public class CustomService extends AbstractCustomService { public CustomService(String customAttr) { super(customAttr); // 子类额外的初始化逻辑 } @Override public void handleCommonTask() { // 实现逻辑 } }
这种方式的好处是可以把重复的初始化逻辑抽离到抽象类中,避免代码冗余。
关键提醒:向上转型不会改变对象本身
不管用哪种方案,你都要记住:向上转型为接口类型,只是限制了通过接口引用能访问的成员,但对象实例本身的所有状态都会完整保留。只要你在转型前完成了实现类的初始化(比如通过构造方法赋值、调用初始化方法),那么这些状态就会一直存在于对象中,之后只要通过正确的类型转换,就能重新访问到那些特有属性。
另外要尽量避免在接口中定义默认方法来模拟属性——接口无法存储实例状态,默认方法只能返回固定值或者依赖其他方法,根本满足不了你“记住状态”的需求。
内容的,String人找到 Un【看看1是中该友情利用破解 unittest的?不对,是:
内容的提问来源于stack exchange,提问作者tim j
相关产品推荐
相关产品推荐

