美文网首页
工厂设计模式 Factory Design Pattern

工厂设计模式 Factory Design Pattern

作者: _浅墨_ | 来源:发表于2022-02-15 20:51 被阅读0次

工厂设计模式,用于封装遵循特定公共接口的实体的实现细节。

下面是一个示例(一个生产水果的工厂):

enum FruitType {
    case apple, orange
}

protocol Fruit {
    var name: String { get }
}

struct Apple: Fruit {
    let name = "Apple"
}

struct Orange: Fruit {
    let name = "Orange"
}

class FruitFactory {
    static let shared = FruitFactory()
    private init() { }
    
    func makeFruit(ofType type: FruitType) -> Fruit {
        switch type {
        case .apple:
            return Apple()
        case .orange:
            return Orange()
        }
    }
}

使用方法:

let apple = FruitFactory.shared.makeFruit(ofType: .apple)
let orange = FruitFactory.shared.makeFruit(ofType: .orange)

这样,根据传入类型,就可以获得某种水果。用户完全不用关心具体实现细节。

相关文章

网友评论

      本文标题:工厂设计模式 Factory Design Pattern

      本文链接:https://www.haomeiwen.com/subject/ssxllrtx.html