逆寒手游活动资讯网

揭秘iOS开发:23种设计模式实战解析与应用

引言

在iOS开发领域,设计模式是提高代码可维护性、可扩展性和可重用性的关键。本文将深入解析23种经典的设计模式,并通过实战案例展示如何在iOS开发中应用这些模式。

1. 单例模式(Singleton)

单例模式确保一个类只有一个实例,并提供一个全局访问点。在iOS开发中,单例模式常用于管理配置、数据库连接等。

class Singleton {

static let shared = Singleton()

private init() {}

func someMethod() {

// 实现方法

}

}

2. 工厂模式(Factory Method)

工厂模式定义一个接口用于创建对象,但让子类决定实例化哪个类。在iOS开发中,工厂模式常用于创建复杂对象。

protocol Factory {

func createObject() -> Any

}

class ConcreteFactory: Factory {

func createObject() -> Any {

return ConcreteProduct()

}

}

class ConcreteProduct {

// 实现产品

}

3. 抽象工厂模式(Abstract Factory)

抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。

protocol AbstractFactory {

func createProductA() -> ProductA

func createProductB() -> ProductB

}

class ConcreteFactory1: AbstractFactory {

func createProductA() -> ProductA {

return ProductA1()

}

func createProductB() -> ProductB {

return ProductB1()

}

}

class ProductA1: ProductA {

// 实现产品A

}

class ProductB1: ProductB {

// 实现产品B

}

4. 建造者模式(Builder)

建造者模式将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

class Builder {

func createPartA() {

// 构建部分A

}

func createPartB() {

// 构建部分B

}

func getResult() -> Product {

return Product()

}

}

class Director {

func construct(builder: Builder) {

builder.createPartA()

builder.createPartB()

}

}

class Product {

// 产品

}

5. 原型模式(Prototype)

原型模式通过复制现有的实例来创建新的实例,而不是通过构造函数。

class Prototype {

func clone() -> Prototype {

return Prototype()

}

}

6. 适配器模式(Adapter)

适配器模式允许将一个类的接口转换成客户期望的另一个接口。在iOS开发中,适配器模式常用于集成第三方库。

protocol Target {

func request()

}

protocol Adapter: Target {

func adapt()

}

class ConcreteAdapter: Adapter {

func adapt() {

// 调用原始类的接口

}

func request() {

adapt()

}

}

7. 桥接模式(Bridge)

桥接模式将抽象部分与实现部分分离,使它们可以独立地变化。

protocol Abstraction {

func operation()

}

protocol Implementation {

func operationImp()

}

class RefinedAbstraction: Abstraction {

private let implementation: Implementation

init(implementation: Implementation) {

self.implementation = implementation

}

func operation() {

implementation.operationImp()

}

}

class ConcreteImplementationA: Implementation {

func operationImp() {

// 实现细节

}

}

8. 组合模式(Composite)

组合模式将对象组合成树形结构以表示“部分-整体”的层次结构。

protocol Component {

func operation()

}

class Leaf: Component {

func operation() {

// 叶子节点操作

}

}

class Composite: Component {

private var components: [Component] = []

func add(_ component: Component) {

components.append(component)

}

func operation() {

for component in components {

component.operation()

}

}

}

9. 装饰者模式(Decorator)

装饰者模式动态地给一个对象添加一些额外的职责,而不改变其接口。

protocol Component {

func operation()

}

class ConcreteComponent: Component {

func operation() {

// 实现细节

}

}

class Decorator: Component {

private let component: Component

init(component: Component) {

self.component = component

}

func operation() {

component.operation()

// 添加额外职责

}

}

10. 外观模式(Facade)

外观模式提供了一个统一的接口,用来访问子系统中的一群接口。

protocol Facade {

func operationA()

func operationB()

}

class SubsystemA {

func operationA() {

// 实现细节

}

}

class SubsystemB {

func operationB() {

// 实现细节

}

}

class FacadeImplementation: Facade {

private let subsystemA = SubsystemA()

private let subsystemB = SubsystemB()

func operationA() {

subsystemA.operationA()

}

func operationB() {

subsystemB.operationB()

}

}

11. 享元模式(Flyweight)

享元模式通过共享尽可能多的相似对象来减少内存使用。

protocol Flyweight {

func operation(context: Context)

}

class ConcreteFlyweight: Flyweight {

func operation(context: Context) {

// 实现细节

}

}

class Context {

var extrinsicState: String

init(extrinsicState: String) {

self.extrinsicState = extrinsicState

}

}

12. 代理模式(Proxy)

代理模式为其他对象提供一种代理以控制对这个对象的访问。

protocol Subject {

func request()

}

class RealSubject: Subject {

func request() {

// 实现细节

}

}

class Proxy: Subject {

private let realSubject: RealSubject

init(realSubject: RealSubject) {

self.realSubject = realSubject

}

func request() {

// 代理逻辑

realSubject.request()

}

}

13. 观察者模式(Observer)

观察者模式定义对象间的一对多依赖关系,当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。

protocol Observer {

func update(subject: Subject)

}

protocol Subject {

func attach(observer: Observer)

func detach(observer: Observer)

func notifyObservers()

}

class ConcreteSubject: Subject {

private var observers: [Observer] = []

func attach(observer: Observer) {

observers.append(observer)

}

func detach(observer: Observer) {

observers.removeValue(forKey: observer)

}

func notifyObservers() {

for observer in observers {

observer.update(subject: self)

}

}

func changeState() {

notifyObservers()

}

}

class ConcreteObserver: Observer {

func update(subject: Subject) {

// 更新逻辑

}

}

14. 状态模式(State)

状态模式允许对象在其内部状态改变时改变其行为。

protocol State {

func handle(context: Context)

}

class ConcreteStateA: State {

func handle(context: Context) {

// 实现细节

}

}

class ConcreteStateB: State {

func handle(context: Context) {

// 实现细节

}

}

class Context {

private var state: State

init(state: State) {

self.state = state

}

func setState(_ state: State) {

self.state = state

}

func request() {

state.handle(context: self)

}

}

15. 策略模式(Strategy)

策略模式定义一系列算法,把它们一个个封装起来,并使它们可互相替换。

protocol Strategy {

func execute()

}

class ConcreteStrategyA: Strategy {

func execute() {

// 实现细节

}

}

class ConcreteStrategyB: Strategy {

func execute() {

// 实现细节

}

}

class Context {

private var strategy: Strategy

init(strategy: Strategy) {

self.strategy = strategy

}

func setStrategy(_ strategy: Strategy) {

self.strategy = strategy

}

func executeStrategy() {

strategy.execute()

}

}

16. 模板方法模式(Template Method)

模板方法模式定义一个操作中的算法的骨架,将一些步骤延迟到子类中。

protocol TemplateMethod {

func templateMethod()

}

class ConcreteClassA: TemplateMethod {

func templateMethod() {

// 实现细节

}

func hookMethod() {

// 可选方法

}

}

class ConcreteClassB: TemplateMethod {

func templateMethod() {

// 实现细节

}

func hookMethod() {

// 实现细节

}

}

17. 迭代器模式(Iterator)

迭代器模式提供了一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

protocol Iterator {

func first()

func next()

func isDone() -> Bool

func currentItem() -> Element

}

class ConcreteIterator: Iterator {

private var elements: [Element]

private var currentIndex: Int

init(elements: [Element]) {

self.elements = elements

self.currentIndex = 0

}

func first() {

currentIndex = 0

}

func next() {

currentIndex += 1

}

func isDone() -> Bool {

return currentIndex >= elements.count

}

func currentItem() -> Element {

return elements[currentIndex]

}

}

18. 访问者模式(Visitor)

访问者模式表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作。

protocol Visitor {

func visit(element: ElementA)

func visit(element: ElementB)

}

protocol Element {

func accept(visitor: Visitor)

}

class ElementA: Element {

func accept(visitor: Visitor) {

visitor.visit(element: self)

}

func operationA() {

// 实现细节

}

}

class ElementB: Element {

func accept(visitor: Visitor) {

visitor.visit(element: self)

}

func operationB() {

// 实现细节

}

}

class ConcreteVisitor: Visitor {

func visit(element: ElementA) {

element.operationA()

}

func visit(element: ElementB) {

element.operationB()

}

}

19. 中介者模式(Mediator)

中介者模式定义一个对象来封装一组对象之间的交互,使对象之间不需要显式地相互引用,从而降低它们之间的耦合。

protocol Mediator {

func addColleague(colleague: Colleague)

func communicate(from: Colleague, to: Colleague, message: String)

}

protocol Colleague {

func send(message: String, to: Colleague)

func receive(message: String)

}

class ConcreteMediator: Mediator {

private var colleagues: [Colleague] = []

func addColleague(colleague: Colleague) {

colleagues.append(colleague)

}

func communicate(from: Colleague, to: Colleague, message: String) {

to.receive(message: message)

}

}

class ConcreteColleagueA: Colleague {

private let mediator: Mediator

init(mediator: Mediator) {

self.mediator = mediator

}

func send(message: String, to: Colleague) {

mediator.communicate(from: self, to: to, message: message)

}

func receive(message: String) {

// 接收消息

}

}

20. 命令模式(Command)

命令模式将请求封装为一个对象,从而允许用户使用不同的请求、队列或日志请求,以及支持可撤销的操作。

protocol Command {

func execute()

}

class ConcreteCommand: Command {

private let receiver: Receiver

init(receiver: Receiver) {

self.receiver = receiver

}

func execute() {

receiver.action()

}

}

class Receiver {

func action() {

// 实现细节

}

}

class Invoker {

private let command: Command

init(command: Command) {

self.command = command

}

func call() {

command.execute()

}

}

21. 职责链模式(Chain of Responsibility)

职责链模式使多个对象都有机会处理请求,从而避免请求发送者和接收者之间的耦合关系。

protocol Handler {

func handle(request: Request)

func setNextHandler(_ handler: Handler)

}

class ConcreteHandlerA: Handler {

private var nextHandler: Handler?

func handle(request: Request) {

// 处理请求

if let nextHandler = nextHandler {

nextHandler.handle(request: request)

}

}

func setNextHandler(_ handler: Handler) {

nextHandler = handler

}

}

class ConcreteHandlerB: Handler {

private var nextHandler: Handler?

func handle(request: Request) {

// 处理请求

if let nextHandler = nextHandler {

nextHandler.handle(request: request)

}

}

func setNextHandler(_ handler: Handler) {

nextHandler = handler

}

}

class Request {

// 请求

}

22. 模板方法模式(Template Method)

模板方法模式定义一个操作中的算法的骨架,将一些步骤延迟到子类中。

protocol TemplateMethod {

func templateMethod()

}

class ConcreteClassA: TemplateMethod {

func templateMethod() {

// 实现细节

}

func hookMethod() {

// 可选方法

}

}

class ConcreteClassB: TemplateMethod {

func templateMethod() {

// 实现细节

}

func hookMethod() {

// 实现细节

}

}

23. 迭代器模式(Iterator)

迭代器模式提供了一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

protocol Iterator {

func first()

func next()

func isDone() -> Bool

func currentItem() -> Element

}

class ConcreteIterator: Iterator {

private var elements: [Element]

private var currentIndex: Int

init(elements: [Element]) {

self.elements = elements

self.currentIndex = 0

}

func first() {

currentIndex = 0

}

func next() {

currentIndex += 1

}

func isDone() -> Bool {

return currentIndex >= elements.count

}

func currentItem() -> Element {

return elements[currentIndex]

}

}

总结

本文深入解析了23种经典的设计模式,并通过实战案例展示了如何在iOS开发中应用这些模式。掌握这些设计模式将有助于提高代码质量,提高开发效率。希望本文对您有所帮助。

2026-01-23 13:47:27


照片如何在PS换背景?超详细教程,新手也能1分钟搞定
从5W到240W:手机快充功率全面解析