实例解析Ruby设计模式编程中Strategy策略模式的使用

2019-09-25 09:38:38刘景俊

class Strategy 
  def get_sql usernames 
    raise "You should override this method in subclass." 
  end 
end 

然后定义两个子类都继承上述父类,并将两种拼装SQL语句的算法分别加入两个子类中:

class Strategy1 
  def get_sql usernames 
    sql = "select * from user_info where " 
    usernames.each do |user| 
      sql << "username = '" 
      sql << user 
      sql << "' or " 
    end 
    sql = sql[0 .. -" or ".length] 
  end 
end 

class Strategy2 
  def get_sql usernames 
    sql = "select * from user_info where " 
    need_or = false 
    usernames.each do |user| 
      sql << " or " if need_or 
      sql << "username = '" 
      sql << user 
      sql << "'" 
      need_or = true 
    end 
  end 
end 

然后在QueryUtil的find_user_info方法中调用Strategy的get_sql方法就可以获得拼装好的SQL语句,代码如下所示:

require 'mysql' 
 
class QueryUtil 
  def find_user_info(usernames, strategy) 
    @db = Mysql.real_connect("localhost","root","123456","test",3306); 
    sql = strategy.get_sql(usernames) 
    puts sql 
    result = @db.query(sql); 
    result.each_hash do |row| 
      #处理从数据库读出来的数据 
    end 
    #后面应将读到的数据组装成对象返回,这里略去 
  ensure 
    @db.close 
  end 
end 

最后,测试代码在调用find_user_info方法时,只需要显示地指明需要使用哪一个策略对象就可以了:

qUtil = QueryUtil.new 
qUtil.find_user_info(["Tom", "Jim", "Anna"], Strategy1.new) 
qUtil.find_user_info(["Jac", "Joe", "Rose"], Strategy2.new) 

打印出的SQL语句丝毫不出预料,如下所示:

select * from user_info where username = 'Tom' or username = 'Jim' or username = 'Anna' 
select * from user_info where username = 'Jac' or username = 'Joe' or username = 'Rose' 

使用策略模式修改之后,代码的可读性和扩展性都有了很大的提高,即使以后还需要添加新的算法,你也是手到擒来了!

策略模式和简单工厂模式结合的实例

需求:

商场收银软件,根据客户购买物品的单价和数量,计算费用,会有促销活动,打八折,满三百减一百之类的。

1.使用工厂模式

# -*- encoding: utf-8 -*-

#现金收费抽象类
class CashSuper
  def accept_cash(money)
  end
end

#正常收费子类
class CashNormal < CashSuper
  def accept_cash(money)
    money
  end
end

#打折收费子类
class CashRebate < CashSuper
  attr_accessor :mony_rebate
  
  def initialize(mony_rebate)
    @mony_rebate = mony_rebate
  end

  def accept_cash(money)
    money * mony_rebate
  end
end

#返利收费子类
class CashReturn < CashSuper
  attr_accessor :mony_condition, :mony_return
  
  def initialize(mony_condition, mony_return)
    @mony_condition = mony_condition
    @mony_return = mony_return
  end

  def accept_cash(money)
    if money > mony_condition
      money - (money/mony_condition) * mony_return
    end
  end
end

#现金收费工厂类
class CashFactory
  def self.create_cash_accept(type)
    case type
    when '正常收费'
      CashNormal.new()
    when '打8折'
      CashRebate.new(0.8)
    when '满三百减100'
      CashReturn.new(300,100)
    end
  end
end

cash0 = CashFactory.create_cash_accept('正常收费')
p cash0.accept_cash(700)

cash1 = CashFactory.create_cash_accept('打8折')
p cash1.accept_cash(700)

cash2 = CashFactory.create_cash_accept('满三百减100')
p cash2.accept_cash(700)