责任链模式 Chain Of Responsibility

阅读更多
责任链模式是适用于流程样式过程,比如流水线,OA审批过程
优点:各司其职,便于扩展

 

缺点:每一次必须走流程,按照步骤走
我们使用责任链来解决一个货币找零问题——要求找零是张数最少
描述:将一定数量的金额兑换出张数最少的纸币(目前币种有 100,50 ,20,10, , 1,, 0.1)
比如:102= 100 * 1 + 1*2   125 = 100 *1 …
分析:这个就是一个流程问题,先从最大币值开始,一直往下走,这样纸币的数量才会最少
先定义纸币的枚举类型
enum iConKind: Int {
   
case Jiao = 1
   
case Yuan = 10
   
case Ten = 100
   
case Twenty = 200
   
case Fifty = 500
   
case Hundred = 1000
}
然后定义纸币的实体lei
public class Money {
   
private var realMoney: Float ?
   
internal var total: Float ?{
       
didSet {
        
realMoney = self . total ! * 10
        }
    }
   
public var nextMoney: Money ?
   
var kind: iConKind
   
   
init ( moneyKind: iConKind , nextOne: Money ?){
       
self . kind = moneyKind
       
self . nextMoney = nextOne
    }
   
public func doExchange(){
   
       
if let next = self . nextMoney {
           
var nextTotal = self . realMoney ! % Float ( self . kind . rawValue )
            next.
total = nextTotal / Float ( 10 )
            next.
doExchange ()
           
var number = Int ( self . realMoney !) / self . kind . rawValue
       
println ( " 币种 \ ( self . kind . rawValue / 10 ) 个数 \ ( number )" )
        }
else {
       
println ( " 币种   \ ( self . kind . rawValue ) 个数 \ ( Int ( self . total !* 10 ) )" )
        }
    }
}
 
使用
var jiao = Money (moneyKind: . Jiao , nextOne: nil )
var yuan = Money (moneyKind: . Yuan , nextOne: jiao )
var ten = Money (moneyKind: . Ten , nextOne: yuan )
var twenty = Money (moneyKind: . Twenty , nextOne: ten )
var fifty = Money (moneyKind: . Fifty , nextOne: twenty )
var hundred = Money (moneyKind: . Hundred , nextOne: fifty )
hundred . total = 188.8
hundred . doExchange ()

你可能感兴趣的:(swift,责任链模式)