Method accepting two different types as parameter

前端 未结 8 1860
無奈伤痛
無奈伤痛 2020-12-13 00:39

I am writing a method that should accept as its parameter an object of one of two types which do not share a parent type other than Object. For example, the types are Dreams

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 00:56

    How about this:

    interface ICrushable {
        void crush();
    }
    
    utterlyDestroy(ICrushable parameter) {
        // Very long crushing process goes here
        parameter.crush()
    }
    
    utterlyDestroy(Dreams parameter) {
        utterlyDestroy(new ICrushable() { crush() {parameter.crush();});
    }
    
    utterlyDestroy(Garlic parameter) {
        utterlyDestroy(new ICrushable() { crush() {parameter.crush();});
    }
    

    New development should implement the ICrushable interface, but for the existing Classes, the parameter is wrapped in an ICrushable and passed to the utterlyDestroy(ICrushable) that does all the work.

提交回复
热议问题