在Swift编程的世界里,设计模式是提升代码可读性、可维护性和可扩展性的关键。下面,我将详细介绍20个在Swift编程中不可不知的经典设计模式,并附上相应的应用案例,帮助您从入门到精通。
1. 单例模式(Singleton)
定义:确保一个类只有一个实例,并提供一个全局访问点。
应用案例:
class AppManager {
static let shared = AppManager()
private init() {}
func startApp() {
print("App started")
}
}
let appManager = AppManager.shared
appManager.startApp()
2. 工厂模式(Factory Method)
定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类。
应用案例:
protocol Vehicle {
func drive()
}
class Car: Vehicle {
func drive() {
print("Driving a car")
}
}
class Truck: Vehicle {
func drive() {
print("Driving a truck")
}
}
class VehicleFactory {
func createVehicle(type: String) -> Vehicle {
switch type {
case "car":
return Car()
case "truck":
return Truck()
default:
return Car()
}
}
}
3. 抽象工厂模式(Abstract Factory)
定义:创建相关或依赖对象的家族,而不需要明确指定具体类。
应用案例:
protocol Engine {
func start()
}
class ElectricEngine: Engine {
func start() {
print("Electric engine started")
}
}
class PetrolEngine: Engine {
func start() {
print("Petrol engine started")
}
}
protocol Transmission {
func shiftGear()
}
class AutomaticTransmission: Transmission {
func shiftGear() {
print("Automatic transmission shifted")
}
}
class ManualTransmission: Transmission {
func shiftGear() {
print("Manual transmission shifted")
}
}
class CarFactory {
func createEngine() -> Engine {
return ElectricEngine()
}
func createTransmission() -> Transmission {
return AutomaticTransmission()
}
}
4. 建造者模式(Builder)
定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
应用案例:
class Person {
var name: String
var age: Int
var address: String
init(name: String, age: Int, address: String) {
self.name = name
self.age = age
self.address = address
}
}
class PersonBuilder {
private var name: String?
private var age: Int?
private var address: String?
func setName(name: String) -> PersonBuilder {
self.name = name
return self
}
func setAge(age: Int) -> PersonBuilder {
self.age = age
return self
}
func setAddress(address: String) -> PersonBuilder {
self.address = address
return self
}
func build() -> Person {
return Person(name: name!, age: age!, address: address!)
}
}
let person = PersonBuilder()
.setName(name: "John Doe")
.setAge(age: 30)
.setAddress(address: "123 Main St")
.build()
5. 原型模式(Prototype)
定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
应用案例:
class Document {
var content: String
init(content: String) {
self.content = content
}
func clone() -> Document {
return Document(content: self.content)
}
}
let originalDocument = Document(content: "Hello, World!")
let clonedDocument = originalDocument.clone()
6. 适配器模式(Adapter)
定义:将一个类的接口转换成客户期望的另一个接口,适配器让原本接口不兼容的类可以合作无间。
应用案例:
protocol Target {
func request()
}
class Adaptee {
func specificRequest() {
print("Specific request")
}
}
class Adapter: Target {
private let adaptee = Adaptee()
func request() {
adaptee.specificRequest()
}
}
let target = Adapter()
target.request()
7. 桥接模式(Bridge)
定义:将抽象部分与实现部分分离,使它们都可以独立地变化。
应用案例:
protocol BridgeInterface {
func operation()
}
class RefinedAbstraction: BridgeInterface {
private let implementation: BridgeImplementation
init(implementation: BridgeImplementation) {
self.implementation = implementation
}
func operation() {
implementation.operationImp()
}
}
class BridgeImplementation {
func operationImp() {
print("Implementation operation")
}
}
let implementation = BridgeImplementation()
let abstraction = RefinedAbstraction(implementation: implementation)
abstraction.operation()
8. 组合模式(Composite)
定义:将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
应用案例:
protocol Component {
func operation()
}
class Leaf: Component {
func operation() {
print("Leaf operation")
}
}
class Composite: Component {
private var components = [Component]()
func add(_ component: Component) {
components.append(component)
}
func operation() {
for component in components {
component.operation()
}
}
}
let leaf = Leaf()
let composite = Composite()
composite.add(leaf)
composite.operation()
9. 装饰者模式(Decorator)
定义:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更为灵活。
应用案例:
protocol Component {
func operation()
}
class ConcreteComponent: Component {
func operation() {
print("ConcreteComponent operation")
}
}
class Decorator: Component {
private let component: Component
init(component: Component) {
self.component = component
}
func operation() {
component.operation()
}
}
class ConcreteDecoratorA: Decorator {
override func operation() {
super.operation()
print("ConcreteDecoratorA operation")
}
}
let component = ConcreteComponent()
let decorator = ConcreteDecoratorA(component: component)
decorator.operation()
10. 外观模式(Facade)
定义:为子系统中的一组接口提供一个统一的接口,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
应用案例:
class SubsystemA {
func operationA() {
print("SubsystemA operationA")
}
}
class SubsystemB {
func operationB() {
print("SubsystemB operationB")
}
}
class Facade {
private let subsystemA = SubsystemA()
private let subsystemB = SubsystemB()
func operation() {
subsystemA.operationA()
subsystemB.operationB()
}
}
let facade = Facade()
facade.operation()
11. 享元模式(Flyweight)
定义:运用共享技术有效地支持大量细粒度的对象。
应用案例:
class Flyweight {
var sharedState: String
var uniqueState: String
init(sharedState: String, uniqueState: String) {
self.sharedState = sharedState
self.uniqueState = uniqueState
}
func operation() {
print("Shared State: \(sharedState), Unique State: \(uniqueState)")
}
}
class FlyweightFactory {
private var flyweights = [String: Flyweight]()
func getFlyweight(sharedState: String, uniqueState: String) -> Flyweight {
if let flyweight = flyweights[sharedState] {
return flyweight
} else {
let flyweight = Flyweight(sharedState: sharedState, uniqueState: uniqueState)
flyweights[sharedState] = flyweight
return flyweight
}
}
}
let factory = FlyweightFactory()
let flyweight1 = factory.getFlyweight(sharedState: "A", uniqueState: "1")
let flyweight2 = factory.getFlyweight(sharedState: "A", uniqueState: "2")
flyweight1.operation()
flyweight2.operation()
12. 代理模式(Proxy)
定义:为其他对象提供一种代理以控制对这个对象的访问。
应用案例:
protocol Image {
func draw()
}
class RealImage: Image {
private let fileName: String
init(fileName: String) {
self.fileName = fileName
print("Loading \(fileName)")
}
func draw() {
print("Drawing \(fileName)")
}
}
class ProxyImage: Image {
private let fileName: String
private var realImage: RealImage?
init(fileName: String) {
self.fileName = fileName
}
func draw() {
if realImage == nil {
realImage = RealImage(fileName: fileName)
}
realImage?.draw()
}
}
let image = ProxyImage(fileName: "test_image.jpg")
image.draw()
13. 职责链模式(Chain of Responsibility)
定义:使多个对象都有机会处理请求,从而避免请求发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它。
应用案例:
protocol Handler {
func handle(request: String)
var nextHandler: Handler? { get set }
}
class ConcreteHandlerA: Handler {
var nextHandler: Handler?
func handle(request: String) {
if request.hasPrefix("A") {
print("ConcreteHandlerA handles request: \(request)")
} else if let nextHandler = nextHandler {
nextHandler.handle(request: request)
}
}
}
class ConcreteHandlerB: Handler {
var nextHandler: Handler?
func handle(request: String) {
if request.hasPrefix("B") {
print("ConcreteHandlerB handles request: \(request)")
} else if let nextHandler = nextHandler {
nextHandler.handle(request: request)
}
}
}
let handlerA = ConcreteHandlerA()
let handlerB = ConcreteHandlerB()
handlerA.nextHandler = handlerB
handlerA.handle(request: "A1")
handlerA.handle(request: "B2")
14. 命令模式(Command)
定义:将请求封装为一个对象,从而允许用户使用不同的请求、队列或日志请求,以及支持可撤销的操作。
应用案例:
protocol Command {
func execute()
}
class Light {
func turnOn() {
print("Light turned on")
}
func turnOff() {
print("Light turned off")
}
}
class LightOnCommand: Command {
private let light: Light
init(light: Light) {
self.light = light
}
func execute() {
light.turnOn()
}
}
class LightOffCommand: Command {
private let light: Light
init(light: Light) {
self.light = light
}
func execute() {
light.turnOff()
}
}
class RemoteControl {
private var command: Command?
func setCommand(_ command: Command) {
self.command = command
}
func pressButton() {
command?.execute()
}
}
let light = Light()
let lightOnCommand = LightOnCommand(light: light)
let lightOffCommand = LightOffCommand(light: light)
let remoteControl = RemoteControl()
remoteControl.setCommand(lightOnCommand)
remoteControl.pressButton()
remoteControl.setCommand(lightOffCommand)
remoteControl.pressButton()
15. 解释器模式(Interpreter)
定义:为语言创建解释器,该解释器使用语法分析器来读取语言,构造抽象语法树,然后遍历这棵树来解释语言中的句子。
应用案例:
protocol Expression {
func interpret(context: Context) -> Int
}
class TerminalExpression: Expression {
func interpret(context: Context) -> Int {
return context.get("Terminal")
}
}
class OrExpression: Expression {
private let expression1: Expression
private let expression2: Expression
init(expression1: Expression, expression2: Expression) {
self.expression1 = expression1
self.expression2 = expression2
}
func interpret(context: Context) -> Int {
let value1 = expression1.interpret(context: context)
let value2 = expression2.interpret(context: context)
return value1 | value2
}
}
class Context {
private var variables = [String: Int]()
func get(key: String) -> Int {
return variables[key] ?? 0
}
func set(key: String, value: Int) {
variables[key] = value
}
}
let context = Context()
context.set(key: "A", value: 1)
context.set(key: "B", value: 1)
let expression = OrExpression(expression1: TerminalExpression(), expression2: TerminalExpression())
let result = expression.interpret(context: context)
print(result)
16. 迭代器模式(Iterator)
定义:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
应用案例:
class Aggregate {
private var elements = [String]()
func add(element: String) {
elements.append(element)
}
func iterator() -> AggregateIterator {
return AggregateIterator(elements: elements)
}
}
class AggregateIterator {
private var elements: [String]
private var position = 0
init(elements: [String]) {
self.elements = elements
}
func hasNext() -> Bool {
return position < elements.count
}
func next() -> String {
return elements[position]
}
}
let aggregate = Aggregate()
aggregate.add(element: "Element 1")
aggregate.add(element: "Element 2")
aggregate.add(element: "Element 3")
let iterator = aggregate.iterator()
while iterator.hasNext() {
print(iterator.next())
}
17. 中介者模式(Mediator)
定义:定义一个对象来封装一组对象之间的交互,使得对象之间不需要显式地相互引用,从而降低它们之间的耦合。
应用案例:
protocol Mediator {
func send(message: String, from: Colleague)
}
protocol Colleague {
func send(message: String, to: Colleague)
func receive(message: String)
}
class ConcreteMediator: Mediator {
private var colleagues = [Colleague]()
func add(colleague: Colleague) {
colleagues.append(colleague)
}
func send(message: String, from: Colleague) {
for colleague in colleagues {
if colleague !== from {
colleague.receive(message: message)
}
}
}
}
class ConcreteColleagueA: Colleague {
var mediator: Mediator?
func send(message: String, to: Colleague) {
mediator?.send(message: message, from: self)
}
func receive(message: String) {
print("Colleague A received: \(message)")
}
}
class ConcreteColleagueB: Colleague {
var mediator: Mediator?
func send(message: String, to: Colleague) {
mediator?.send(message: message, from: self)
}
func receive(message: String) {
print("Colleague B received: \(message)")
}
}
let mediator = ConcreteMediator()
let colleagueA = ConcreteColleagueA()
let colleagueB = ConcreteColleagueB()
mediator.add(colleague: colleagueA)
mediator.add(colleague: colleagueB)
colleagueA.send(message: "Hello from A", to: colleagueB)
18. 观察者模式(Observer)
定义:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。
应用案例:
protocol Observer {
func update()
}
class Subject {
private var observers = [Observer]()
func addObserver(_ observer: Observer) {
observers.append(observer)
}
func notifyObservers() {
for observer in observers {
observer.update()
}
}
func changeState() {
notifyObservers()
}
}
class ConcreteObserverA: Observer {
func update() {
print("Observer A updated")
}
}
class ConcreteObserverB: Observer {
func update() {
print("Observer B updated")
}
}
let subject = Subject()
let observerA = ConcreteObserverA()
let observerB = ConcreteObserverB()
subject.addObserver(observerA)
subject.addObserver(observerB)
subject.changeState()
19. 状态模式(State)
定义:允许一个对象在其内部状态改变时改变它的行为。
应用案例:
protocol State {
func handle(context: Context)
}
class ConcreteStateA: State {
func handle(context: Context) {
context.setState(state: ConcreteStateB())
}
}
class ConcreteStateB: State {
func handle(context: Context) {
context.setState(state: ConcreteStateA())
}
}
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)
}
}
let context = Context(state: ConcreteStateA())
context.request()
context.request()
20. 访问者模式(Visitor)
定义:表示一个作用于某对象结构中的各元素的操作,它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作。
应用案例:
protocol Visitor {
func visit(element: Element)
}
class ConcreteVisitorA: Visitor {
func visit(element: Element) {
print("ConcreteVisitorA visits \(element)")
}
}
class ConcreteVisitorB: Visitor {
func visit(element: Element) {
print("ConcreteVisitorB visits \(element)")
}
}
protocol Element {
func accept(visitor: Visitor)
}
class ConcreteElementA: Element {
func accept(visitor: Visitor) {
visitor.visit(element: self)
}
}
class ConcreteElementB: Element {
func accept(visitor: Visitor) {
visitor.visit(element: self)
}
}
let elementA = ConcreteElementA()
let elementB = ConcreteElementB()
let visitorA = ConcreteVisitorA()
elementA.accept(visitor: visitorA)
elementB.accept(visitor: visitorA)
let visitorB = ConcreteVisitorB()
elementA.accept(visitor: visitorB)
elementB.accept(visitor: visitorB)
以上就是我
