Ruby 中的类、模块与加载机制
1. 自定义编组方法
当禁用了类的 clone 和 dup 方法时,为了防止通过对象的转储和加载来创建副本,需要实现自定义的编组方法。可以通过定义 marshal_dump 和 marshal_load 方法抛出异常来完全阻止编组,但这有些强硬。更优雅的解决方案是自定义反编组,使 Marshal.load 返回现有对象而非创建副本。
以下是实现自定义编组方法的示例:
class Season
# We want to allow Season objects to be marshaled, but we don't
# want new instances to be created when they are unmarshaled.
def _dump(limit) # Custom marshaling method
@n.to_s # Return index as a string
end
def self._load(s) # Custom unmarshaling method
INSTANCES[Integer(s)] # Return an existing instance
end
end
2. 单例模式
单例是指只有一个实例的类。单例可用于在面向对象框架中存
超级会员免费看
订阅专栏 解锁全文
364

被折叠的 条评论
为什么被折叠?



