框架设计模式-④适配器模式、策略模式、责任链模式(Adapter、Strategy、Chain of Responsibility)
设计模式
核心概念
场景
适配器模式
将一个类的接口变换成所期待的另一种接口
各支付SDK支付服务接口的整合
策略模式
定义共同行为,各策略遵循,以达到可切换策略
支付SDK的选择、计价方案的选择
责任链模式
添加责任,形成责任链,成功则传递以执行下一个责任
请求拦截器的责任链、内容发布(订单创建)
零、组合模式 场景:评论系统的评论和回复、组织架构、文件系统
判断代码是否使用了组合模式,可以检查以下几个关键点:
对象的树形结构 :代码中是否存在对象的树形结构,即对象间存在父子关系,并且可以递归地组织在一起。
共享接口 :是否定义了一个共享接口或抽象类,它被叶子对象和容器对象所实现或继承。
叶子对象(Leaf) :是否存在叶子对象,它们是树形结构中的末端节点,没有子节点。
如果你在代码中看到了这些特征,那么它很可能使用了组合模式。组合模式的目的是将对象组合成树形结构,并使得客户端可以统一地对待叶子对象和容器对象。
一、适配器模式(Adapter) 适配器模式(Adapter Pattern):将一个类的接口变换成所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。
说人话:这个模式就是用来做适配的,它将不兼容的接口转换为可兼容的接口 ,让原本由于接口不兼容而不能一起工作的类可以一起工作。
案例1:各支付SDK 1.1、背景:假设各支付SDK对外提供的支付接口如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class WeChatPay : NSObject { func payWithMoney (amount : Double , completion : @escaping (Bool , Error ?) -> Void ) { completion(true , nil ) } } class AlipayPayment : NSObject { func payWithAmount (amount : Double , success : (Bool ) -> Void , failure : (Error ) -> Void ) { success(true , nil ) } }
适配器模式,将支付宝支付由 success + failure 改成 completion 方式,使得不兼容的接口转换为可兼容的接口。
1 2 3 4 5 6 7 8 9 10 11 12 13 class AlipayPaymentAdapter : NSObject { private let alipayPayment = AlipayPayment () func payWithAmount (amount : Double , completion : @escaping (Bool , Error ?) -> Void ) { alipayPayment.payWithAmount(amount: amount) { success in if success { completion(true , nil ) } else { completion(false , NSError (domain: "PaymentError" , code: - 1 , userInfo: [NSLocalizedDescriptionKey: "Payment failed" ])) } } } }
1.2、适配器模式优化 1.2.1、适配器模式+面向接口编程 为了更好的使用适配器模式,我们可以通过面向接口编程,提前定义适配器接口(其实这个公共接口也可作为策略接口)。
面向协议编程(POP)和面向接口编程(IOP)都是设计原则,它们都强调了依赖抽象而不是具体实现。在某些方面,面向协议可以看作是面向接口的一个扩展或特定语言环境下的实现。
面向接口编程(IOP) 面向接口编程是一种设计原则,它强调通过接口来定义对象的行为,而不是依赖于具体的类。接口定义了一组方法签名,但不提供实现。类通过实现这些接口来声明它们具有特定的行为。
面向协议编程(POP) 面向协议编程是面向接口编程的一个特定实现,特别是在支持协议的语言(如Swift)中。协议定义了一组方法、属性或其他要求,类、结构体或其他类型的实例需要遵循这些要求。协议可以包含默认实现,这使得它们更加灵活。
包含关系 从概念上讲,面向协议编程可以看作是面向接口编程的一个扩展。在面向协议编程中,你定义协议(类似于接口),但协议提供了更多的功能,如:
默认实现 :协议可以提供方法的默认实现,这在接口中通常不可行。
扩展性 :协议可以被扩展,添加更多的方法或属性。
多重继承 :协议支持多重继承,即一个类可以同时遵循多个协议。
在iOS开发中,实现支付系统集成时,可以使用适配器模式(将不兼容的接口转换为可兼容的接口)来创建一个统一的支付接口,然后为每种支付方式(如支付宝、微信支付)提供一个具体的适配器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 protocol PaymentProtocol { func pay (amount : Double , completion : @escaping (Bool , Error ?) -> Void ) } class WeChatPayAdapter : PaymentProtocol { private let weChatPay = WeChatPay () func pay (amount : Double , completion : @escaping (Bool , Error ?) -> Void ) { weChatPay.payWithMoney(amount: amount, completion: completion) } } class AlipayAdapter : PaymentProtocol { private let alipayPayment = AlipayPayment () func pay (amount : Double , completion : @escaping (Bool , Error ?) -> Void ) { alipayPayment.payWithAmount(amount: amount) { success in if success { completion(true , nil ) } else { completion(false , NSError (domain: "PaymentError" , code: - 1 , userInfo: [NSLocalizedDescriptionKey: "Payment failed" ])) } } } }
案例2:UITableView优化 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @implementation SectionAdapterViewController - (void )viewDidLoad { [super viewDidLoad]; GameCellAdapter *cellAdapter = [[GameCellAdapter alloc] initWithTableView:self .tableView datas:datas]; GameSectionAdapter *fpsSectionAdapter = [[GameSectionAdapter alloc] initWithCellAdapter:cellAdapter sectionTitle:@"FPS Games" sectionHeight:60 ]; GameSectionAdapter *roleSectionAdapter = [[GameSectionAdapter alloc] initWithCellAdapter:cellAdapter sectionTitle:@"Role Play Games" sectionHeight:60 ]; self .adapter = [[GameDetailListAdapter alloc] init]; self .adapter.sections = [@[fpsSectionAdapter, roleSectionAdapter] mutableCopy]; self .tableView.dataSource = self .adapter; self .tableView.delegate = self .adapter; }
以上UITableView使用适配器模式优化的代码摘自:iOS模式分析 使用适配器模式重构TableView
二、策略模式(Strategy) app正常业务请求、埋点请求、数美请求、同盾请求。
为了更好的使用策略模式,经常会配合适配器模式,以使得接口统一。
策略模式(Strategy Pattern)是一种行为设计模式,它定义了一系列的算法,并将每一个算法封装起来,使它们可以互换使用。这种模式让算法的变化独立于使用算法的客户。策略模式属于对象行为型模式,它能够让你根据不同的情况选择不同的算法或行为。
策略模式的主要组成
策略接口(Strategy Interface) :定义了一个公共的接口,各种算法以不同的方式实现这个接口。
具体策略类(Concrete Strategy) :实现策略接口的具体算法。
上下文(Context) :使用策略接口,维护一个对策略对象的引用,可以设置和切换不同的策略。
策略模式的优点
算法的多样性 :可以在运行时选择不同的算法,增加新的算法而不需要修改原有代码。
避免使用多重条件判断 :策略模式可以将算法族封装在不同的策略类中,避免在条件判断中使用大量的if-else或switch-case语句。
扩展性 :增加新的策略时,不需要修改原有代码,符合开闭原则。
策略模式的使用场景
当需要在运行时选择算法或行为时。
当需要避免使用多重条件判断时。
案例1:支付SDK选择 1、不使用策略模式时候,支付接口使用的常见写法: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class PayUtil : NSObject { static func pay (amount : Double , payType : PaymentMethod , completion : @escaping (Bool , Error ?) -> Void ) { if payType == .wechat { WeChatPay ().payWithMoney(amount: amount, completion: completion) } else { AlipayPaymentAdapter ().payWithAmount(amount: amount, completion: completion) } } } PayUtil .pay(amount: 100 , payType:.alipay) { success, error in if success { print ("支付成功" ) } else { print ("支付失败: \(error? .localizedDescription ?? "未知错误" ) " ) } }
2、而使用策略模式时(可配合依赖注入,让解耦性好上加好) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 enum PaymentMethod { case alipay case wechat } class PaymentService { private var paymentAdapter: PaymentProtocol ? func setPaymentMethod (method : PaymentMethod ) { switch method { case .alipay: paymentAdapter = AlipayAdapter () case .wechat: paymentAdapter = WeChatPayAdapter () } } func payment (amount : Double , completion : @escaping (Bool , Error ?) -> Void ) { paymentAdapter? .pay(amount: amount, completion: completion) } } let paymentService = PaymentService ()paymentService.setPaymentMethod(method: .alipay) paymentService.payment(amount: 100 ) { success, error in if success { print ("支付成功" ) } else { print ("支付失败: \(error? .localizedDescription ?? "未知错误" ) " ) } }
3、问:不使用PayUtil,而是选择使用策略模式的原因/使用策略模式的优点? 3.1、更符合开闭原则 当需要添加银联支付时候,即使是使用策略模式,也需要对PaymentService进行修改。即在 PaymentService 中添加一个新的 case 来处理新的支付方式,这样,当需要支付时,可以根据用户选择的支付方式动态地切换支付策略。该操作确实和PayUtil一样涉及到对现有代码的修改,这在一定程度上违反了开闭原则的理想状态,即不应该通过修改现有代码来扩展系统。然而,在实际的软件开发中,完全避免修改任何现有代码是非常困难的,特别是在设计初期可能未能预见到所有未来需求的情况下。开闭原则更多地是一种设计哲学,指导我们尽可能地设计出可扩展的系统,而不是绝对的规则。 但是相比之下使用策略模式对中间类PaymentService改动还是更小的。
3.2、策略接口多的时候相比Util其就更符合开闭原则了 此时策略模式的优势可能还没发挥出来,但当我们的各平台钱包SDK,如果除pay操作外,还有余额查询,查询交易记录等接口时候,策略模式的优势就显示出来了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class PaymentService { private var paymentAdapter: PaymentProtocol ? func setPaymentMethod (method : PaymentMethod ) { switch method { case .alipay: paymentAdapter = AlipayAdapter () case .wechat: paymentAdapter = WeChatPayAdapter () } } func payment (amount : Double , completion : @escaping (Bool , Error ?) -> Void ) { paymentAdapter? .pay(amount: amount, completion: completion) } func checkBalance (completion : @escaping (Bool , Error ?) -> Void ) { paymentAdapter? .pay(completion: completion) } func checkOrders (completion : @escaping (Bool , Error ?) -> Void ) { paymentAdapter? .pay(completion: completion) } }
案例2:计价 假设咖啡添加不同成分时,计价不同,常见的写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 abstract class BaseCoffee { int get price; } class Coffee extends BaseCoffee { Sugar? sugar; Milk? milk; int get price { if (sugar != nil) { if (milk != nil) { return 15 ; } else { return 6 ; } } else { return 10 ; } } }
而使用策略模式时候,会将不同成分的咖啡分成不同策略(策略中有计价方式):
好处:每个策略看起来很简洁,而不是堆在一块。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 protocol PricingStrategy { func calculatePrice () -> Int } struct BasePricingStrategy : PricingStrategy { func calculatePrice () -> Int { return 10 } } struct SugarPricingStrategy : PricingStrategy { func calculatePrice () -> Int { return 6 } } struct MilkPricingStrategy : PricingStrategy { func calculatePrice () -> Int { return 10 } } struct SugarAndMilkPricingStrategy : PricingStrategy { func calculatePrice () -> Int { return 15 } }
调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 class Coffee { var pricingStrategy: PricingStrategy private var _sugar = false private var _milk = false init () { self .pricingStrategy = BasePricingStrategy () } var sugar: Bool { get { return _sugar } set { _sugar = newValue updateStrategy() } } var milk: Bool { get { return _milk } set { _milk = newValue updateStrategy() } } private func updateStrategy () { if _sugar && _milk { self .pricingStrategy = SugarAndMilkPricingStrategy () } else if _sugar { self .pricingStrategy = SugarPricingStrategy () } else if _milk { self .pricingStrategy = MilkPricingStrategy () } else { self .pricingStrategy = BasePricingStrategy () } } func getPrice () -> Int { return pricingStrategy.calculatePrice() } } let coffee = Coffee ()print ("Basic Coffee: \(coffee.getPrice()) " ) coffee.sugar = true print ("Coffee with Sugar: \(coffee.getPrice()) " ) coffee.milk = true print ("Coffee with Sugar and Milk: \(coffee.getPrice()) " ) let coffee2 = Coffee ()coffee2.milk = true print ("Coffee with Milk: \(coffee2.getPrice()) " )
三、责任链模式 常见场景:请求拦截器、内容发布、订单创建(创建前有存不同定金的可获取不同优惠券)
浅谈对责任链模式的理解?应用场景?
场景1:订单创建(创建前有存不同定金的可获取不同优惠券) 场景3:请求拦截器的责任链 场景2:内容发布的责任链
内容验证/检查 :在内容发布之前,可以有一个验证器来检查内容是否符合特定的规则,比如检查是否有敏感词汇、是否符合格式要求等。
权限检查 :在内容发布之前,可以检查用户是否有发布内容的权限。
内容格式化 :内容可能需要经过格式化处理,比如自动添加引用、格式化代码块等。
发布
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 abstract class ContentHandler { bool handleContent(String content); } class ContentChain { List <ContentHandler> _handlers = []; void addHandler(ContentHandler handler) { _handlers.add(handler); } void handle(String content) { for (ContentHandler iHandler in _handlers) { bool success = iHandler.handleContent(content); if (!success) { return ; } } } } void main() { var chain = ContentChain(); chain.addHandler(LogContentHandler()); chain.addHandler(ValidateContentHandler()); chain.addHandler(FormatContentHandler()); chain.addHandler(PublishContentHandler()); chain.handle("This is a sample content with badword." ); } abstract class ContentHandler { void handleContent(String content, Function next); } class LogContentHandler extends ContentHandler { @override bool handleContent(String content) { print ('Logging content: $content ' ); return true ; } } class ValidateContentHandler extends ContentHandler { @override bool handleContent(String content) { if (content.contains('badword' )) { print ('Content validation failed.' ); return false ; } print ('Content is valid.' ); return true ; } } class FormatContentHandler extends ContentHandler { @override bool handleContent(String content) { String formattedContent = content.replaceAll('\n' , '<br/>' ); print ('Formatted content: $formattedContent ' ); return true ; } } class PublishContentHandler extends ContentHandler { @override bool handleContent(String content) { print ('Publishing content: $content ' ); return true ; } }
代码示例中,ContentHandler 抽象类定义了一个 handleContent 方法,该方法返回一个布尔值来指示处理是否成功。ContentChain 类管理处理器链,并在 handle 方法中遍历链中的每个处理器,调用 handleContent 方法,并根据返回值决定是否继续执行。
这种方法确实可以工作,并且它简化了责任链的实现。然而,它有几个潜在的问题:
内容修改 :如果处理器需要修改内容并希望这些修改对后续处理器可见,这种方法就无法满足需求。在当前的设计中,内容的修改不会传递给链中的下一个处理器。
错误处理 :如果某个处理器失败,整个链将停止执行。但是,没有提供一种机制来通知调用者哪个处理器失败了,或者为什么失败。
异步处理(最常见) :如果处理器需要执行异步操作(例如网络请求),当前的设计不支持异步处理。
为了解决这些问题,我们可以对责任链模式进行一些改进。以下是一个改进后的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 abstract class ContentHandler { void handleContent(String content, {required void Function (String ) success, required void Function () failure}); } class LogContentHandler extends ContentHandler { @override void handleContent(String content, {required void Function (String ) success, required void Function () failure}) { print ('Logging content: $content ' ); success(content); } } class ValidateContentHandler extends ContentHandler { @override void handleContent(String content, {required void Function (String ) success, required void Function () failure}) { if (content.contains('badword' )) { print ('Content validation failed.' ); failure(); return ; } print ('Content is valid.' ); success(content); } } class FormatContentHandler extends ContentHandler { @override void handleContent(String content, {required void Function (String ) success, required void Function () failure}) { try { String formattedContent = content.replaceAll('\n' , '<br/>' ); print ('Formatted content: $formattedContent ' ); success(formattedContent); } catch (e) { failure(); } } } class PublishContentHandler extends ContentHandler { @override void handleContent(String content, {required void Function (String ) success, required void Function () failure}) { try { print ('Publishing content: $content ' ); success(content); } catch (e) { failure(); } } } class ContentChain { List <ContentHandler> _handlers = []; void addHandler(ContentHandler handler) { _handlers.add(handler); } void handle(String content) { _functionChain(0 , content); } void _functionChain(int index, String content) { if (index >= _handlers.length) return ; _handlers[index].handleContent(content, success: (String newContent) { _functionChain(index + 1 , newContent); }, failure: () { print ("Error handling content. Stopping the chain." ); } ); } } void main() { var chain = ContentChain(); chain.addHandler(LogContentHandler()); chain.addHandler(ValidateContentHandler()); chain.addHandler(FormatContentHandler()); chain.addHandler(PublishContentHandler()); chain.handle("This is a sample content with badword." ); }
四、装饰器模式 1、继承的缺点 使用继承的缺点包括:
类爆炸 :随着新特性的增加,你需要创建越来越多的子类来组合这些特性,这会导致类的数目急剧增加。
耦合性 :子类与父类高度耦合,父类的任何改变都可能影响到子类。
违反开闭原则 :继承结构通常违反开闭原则,因为添加新功能需要修改现有类。
装饰器模式**通过组合(这里说的不是组合模式)**而不是继承来解决这些问题,提供了更大的灵活性和可扩展性。
装饰模式(Decorator),动态地为一个对象添加额外的职责,是继承的替代方案,属于结构型模式。 通过装饰模式扩展对象的功能比继承子类方式更灵活,使用继承子类的方式,是在编译时静态决定的,即编译时绑定,而且所有的子类都会继承相同的行为。然而,如果使用组合的方式扩展对象的行为,就可以在运行时动态地进行扩展,将来如果需要也可以动态的撤销,而不会影响原类的行为。
实现装饰器模式的关键在于创建一个包装类,该类持有对被装饰对象的引用,并包含被装饰对象的行为。包装类应该能够扩展被装饰对象的行为,并在需要时将其附加到被装饰对象的逻辑中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Student { var name: String init (name : String ) { self .name = name } } class StudentClothes { var student : Student var clothes: String ? init (student : Student ) { self .student = student self .clothes = "校服" } .... } class DetailStudent extends Student { var clothes: String ? }
上述代码参见:ios-装饰器模式
举个例子,如果你有一个Coffee类。但如果你想要为咖啡添加糖或奶,使用继承就不太合适,因为可能会创建出大量的子类(如MilkSugarCoffee、SugarEspresso等),这会导致类的爆炸。这时,装饰器模式就显得更为合适,你可以创建一个CoffeeDecorator类,它包裹一个Coffee对象,并在其中添加添加糖或奶的方法。
使用装饰器模式来为Coffee类添加额外的组件(比如牛奶或糖)时,代码可以按照下面的结构来实现:
附1:策略模式在Flutter中的使用代码示例 常见场景:支付(微信支付、支付宝支付、银联支付、信用卡支付)
缓存?磁盘缓存、内存缓存?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 abstract class PaymentStrategy { void pay(double amount); } class CreditCardPayment implements PaymentStrategy { @override void pay(double amount) { print ('Paying $amount using Credit Card' ); } } class AlipayPayment implements PaymentStrategy { @override void pay(double amount) { print ('Paying $amount using Alipay' ); } } class WeChatPayment implements PaymentStrategy { @override void pay(double amount) { print ('Paying $amount using WeChat Pay' ); } } class ShoppingCart { PaymentStrategy? _paymentStrategy; void setPaymentStrategy(PaymentStrategy? strategy) { _paymentStrategy = strategy; } void checkout(double amount) { _paymentStrategy?.pay(amount); } }
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Strategy Pattern Demo' , theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Strategy Pattern Demo' ), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, this .title}) : super (key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State <MyHomePage > { ShoppingCart _cart = ShoppingCart(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( child: Text('Pay with Credit Card' ), onPressed: () { _cart.setPaymentStrategy(CreditCardPayment()); _cart.checkout(100.0 ); }, ), ElevatedButton( child: Text('Pay with Alipay' ), onPressed: () { _cart.setPaymentStrategy(AlipayPayment()); _cart.checkout(100.0 ); }, ), ElevatedButton( child: Text('Pay with WeChat Pay' ), onPressed: () { _cart.setPaymentStrategy(WeChatPayment()); _cart.checkout(100.0 ); }, ), ], ), ), ); } }
END