gongweixin
V2EX  ›  问与答

求一设计模式

  •  
  •   gongweixin · Nov 11, 2014 · 3753 views
    This topic created in 4375 days ago, the information mentioned may be changed or developed.
    语言环境:java
    情景:
    方法A(), 方法B()的方法体内,前后有大量相同的代码,只有中间有个别一两行代码不同,因为java不支持方法作为参数,所以比较恶心,现在写成switch,case ,类似方法个数越来越多,看着switch,case越来越恶心,有没有比较优雅的写法?
    3 replies  •  2014-11-11 22:30:00 +08:00
    finian
    finian
    Nov 11, 2014❤️1
    1
    不能传方法你就传个对象进去啊

    https://gist.github.com/anonymous/66599b123cf8fbe8f131
    chone
    chone
    Nov 11, 2014 via iPhone❤️1
    2
    相同的逻辑封装在基类里,然后实现不同的子类A和B来完成差异的逻辑。如果非要传函数那就定义一个接口申明回调方法,然后匿名类实现接口方法作为参数传给其他类,java下边的监听器就是这种实现。
    gongweixin
    gongweixin
    OP
    Nov 11, 2014
    3
    @chone @finian 感谢两位提供的建议.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5045 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 07:59 · PVG 15:59 · LAX 23:59 · JFK 02:59
    ♥ Do have faith in what you're doing.