推荐答案
在 Swift 中,常用的设计模式包括但不限于以下几种:
- 单例模式(Singleton Pattern)
- 工厂模式(Factory Pattern)
- 观察者模式(Observer Pattern)
- 代理模式(Delegate Pattern)
- 策略模式(Strategy Pattern)
- 装饰器模式(Decorator Pattern)
- 适配器模式(Adapter Pattern)
- 组合模式(Composite Pattern)
- 命令模式(Command Pattern)
- 模板方法模式(Template Method Pattern)
本题详细解读
1. 单例模式(Singleton Pattern)
单例模式确保一个类只有一个实例,并提供一个全局访问点。在 Swift 中,通常通过 static let 来实现单例。
class Singleton {
static let shared = Singleton()
private init() {}
}2. 工厂模式(Factory Pattern)
工厂模式用于创建对象,而不需要指定具体的类。Swift 中可以通过枚举或类来实现工厂模式。
// www.javascriptcn.com code example
enum VehicleType {
case car, bike
}
class VehicleFactory {
static func createVehicle(type: VehicleType) -> Vehicle {
switch type {
case .car:
return Car()
case .bike:
return Bike()
}
}
}3. 观察者模式(Observer Pattern)
观察者模式允许对象在状态改变时通知其他对象。Swift 中可以通过 NotificationCenter 或自定义观察者实现。
// www.javascriptcn.com code example
class Subject {
private var observers = [Observer]()
func addObserver(_ observer: Observer) {
observers.append(observer)
}
func notifyObservers() {
for observer in observers {
observer.update()
}
}
}4. 代理模式(Delegate Pattern)
代理模式允许一个对象代表另一个对象处理某些任务。Swift 中常用 protocol 来实现代理模式。
// www.javascriptcn.com code example
protocol TaskDelegate: AnyObject {
func taskCompleted()
}
class Task {
weak var delegate: TaskDelegate?
func complete() {
delegate?.taskCompleted()
}
}5. 策略模式(Strategy Pattern)
策略模式允许在运行时选择算法或行为。Swift 中可以通过协议和不同的实现类来实现。
// www.javascriptcn.com code example
protocol Strategy {
func execute()
}
class ConcreteStrategyA: Strategy {
func execute() {
print("Executing Strategy A")
}
}
class Context {
private var strategy: Strategy
init(strategy: Strategy) {
self.strategy = strategy
}
func executeStrategy() {
strategy.execute()
}
}6. 装饰器模式(Decorator Pattern)
装饰器模式允许动态地给对象添加行为。Swift 中可以通过扩展或组合来实现。
// www.javascriptcn.com code example
protocol Coffee {
func cost() -> Double
}
class SimpleCoffee: Coffee {
func cost() -> Double {
return 5.0
}
}
class MilkDecorator: Coffee {
private let coffee: Coffee
init(coffee: Coffee) {
self.coffee = coffee
}
func cost() -> Double {
return coffee.cost() + 2.0
}
}7. 适配器模式(Adapter Pattern)
适配器模式允许不兼容的接口之间进行交互。Swift 中可以通过类或结构体来实现。
// www.javascriptcn.com code example
protocol Target {
func request() -> String
}
class Adaptee {
func specificRequest() -> String {
return "Specific request"
}
}
class Adapter: Target {
private let adaptee: Adaptee
init(adaptee: Adaptee) {
self.adaptee = adaptee
}
func request() -> String {
return adaptee.specificRequest()
}
}8. 组合模式(Composite Pattern)
组合模式允许将对象组合成树形结构以表示“部分-整体”的层次结构。Swift 中可以通过协议和类来实现。
// www.javascriptcn.com code example
protocol Component {
func operation() -> String
}
class Leaf: Component {
func operation() -> String {
return "Leaf"
}
}
class Composite: Component {
private var children = [Component]()
func add(_ component: Component) {
children.append(component)
}
func operation() -> String {
return children.map { $0.operation() }.joined(separator: ", ")
}
}9. 命令模式(Command Pattern)
命令模式将请求封装为对象,从而使你可以用不同的请求对客户进行参数化。Swift 中可以通过类和协议来实现。
// www.javascriptcn.com code example
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() {
print("Receiver action")
}
}10. 模板方法模式(Template Method Pattern)
模板方法模式定义了一个算法的骨架,并允许子类为一个或多个步骤提供实现。Swift 中可以通过类继承来实现。
// www.javascriptcn.com code example
class AbstractClass {
func templateMethod() {
primitiveOperation1()
primitiveOperation2()
}
func primitiveOperation1() {
fatalError("Subclasses must override this method")
}
func primitiveOperation2() {
fatalError("Subclasses must override this method")
}
}
class ConcreteClass: AbstractClass {
override func primitiveOperation1() {
print("Concrete Operation 1")
}
override func primitiveOperation2() {
print("Concrete Operation 2")
}
}