MST
星途 面试题库

面试题:Ruby中策略模式的实现

请用Ruby代码实现一个简单的策略模式,假设有一个文本处理类,有不同的文本格式化策略,比如加粗、加下划线等,要求通过策略模式来灵活切换这些策略。
45.7万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
# 定义策略接口
class TextFormatter
  def format(text)
    raise NotImplementedError, "子类必须实现 format 方法"
  end
end

# 加粗策略
class BoldFormatter < TextFormatter
  def format(text)
    "*#{text}*"
  end
end

# 加下划线策略
class UnderlineFormatter < TextFormatter
  def format(text)
    "_#{text}_"
  end
end

# 文本处理类
class TextProcessor
  def initialize(formatter)
    @formatter = formatter
  end

  def process(text)
    @formatter.format(text)
  end
end

# 使用示例
bold_text = TextProcessor.new(BoldFormatter.new).process("这是加粗文本")
underline_text = TextProcessor.new(UnderlineFormatter.new).process("这是加下划线文本")

puts bold_text
puts underline_text