给定一些实现某些广泛协议或类似协议(例如 FTP)的库,我如何将符合标准的代码与仅需要能够与不那么符合标准的系统配合的代码分开?
一个很好的例子,恕我直言,像 jQuery 这样的库必须考虑所有这些浏览器的特性。必须保持遗留兼容性的项目也可能是此类技术的良好目标受众。
我对 ruby 解决方案特别感兴趣,但也欢迎独立于语言的模式或来自其他语言的好示例。
我已经找到了一个相关问题 https://stackoverflow.com/questions/2245871/how-do-you-cleanly-separate-code-for-backwards-compatibility-from-the-main-code在 stackoverflow 上,但是还有其他方法吗?
- 为不同的模式定义不同的实现(这可以防止您必须将“好的”代码与只是为了保持向后兼容性的代码混合在一起)。理想情况下,遗留层只是符合标准的代码的包装。
- 检测底层系统(浏览器、远程服务器等)符合标准的程度。具体如何完成显然很大程度上取决于具体情况。
- 为特定系统选择正确的实现并透明地将其插入。
- 让用户有机会检查我们所处的模式并强制使用特定模式。
小红宝石示例:
class GoodServer
def calculate(expr)
return eval(expr).to_s
end
end
class QuirkyServer
def calculate(expr)
# quirky server prefixes the result with "result: "
return "result: %s" % eval(expr)
end
end
module GoodClient
def calculate(expr)
@server.calculate(expr)
end
end
# compatibility layer
module QuirkyClient
include GoodClient
def calculate(expr)
super(expr).gsub(/^result: /, '')
end
end
class Client
def initialize(server)
@server = server
# figure out if the server is quirky and mix in the matching module
if @server.calculate("1").include?("result")
extend QuirkyClient
else
extend GoodClient
end
end
end
good_server = GoodServer.new
bad_server = QuirkyServer.new
# we can access both servers using the same interface
client1 = Client.new(good_server)
client2 = Client.new(bad_server)
p client1.is_a? QuirkyClient # => false
p client1.calculate("1 + 2") # => "3"
p client2.is_a? QuirkyClient # => true
p client2.calculate("1 + 2") # => "3"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)