Git Hub
коротко

Паттерн Fabric Method

11 января 2017, 11:33

Оглавление

Фабричный метод

Фабричный метод порождает объекты одного и того же типа.

import Foundation
import UIKit

// Protocol for "Product" 
protocol AppleProduct {

    var name: String {get set}
    var screenSize: Double {get set}
    var price: Double {get set}

    func getProduct() -> String
}

// Protocl for "Creator" 
protocol AppleProductCreator {

    func createProduct() -> AppleProduct
}

// Class for "ConcreteProduct"
class IPhoneProduct: AppleProduct {

    var name: String = "iPhone 6"
    var screenSize: Double = 4.7
    var price: Double = 199.00

    func getProduct() -> String {

        return "Apple product "(name)", with screen size in (screenSize) inch, at proce: $(price)"
    }
}

class IPadProduct: AppleProduct {

    var name: String = "iPad Air 3"
    var screenSize: Double = 10.1
    var price: Double = 499.00

    func getProduct() -> String {

        return "Apple product "(name)", with screen size in (screenSize) inch, at proce: $(price)"
    }
}

// Class for "ConcreteCreator"
class IPhoneProductCreator: AppleProductCreator {

    static let sharedInstance:IPhoneProductCreator = IPhoneProductCreator()

    func createProduct() -> AppleProduct {

        return IPhoneProduct()
    }
}

class IPadProductCreator: AppleProductCreator {

    static let sharedInstance:IPadProductCreator = IPadProductCreator()

    func createProduct() -> AppleProduct {

        return IPadProduct()
    }
}

Применение

let product1: AppleProduct = IPhoneProductCreator.sharedInstance.createProduct()
print("Got a new device: " + product1.getProduct())

let product2: AppleProduct = IPadProductCreator.sharedInstance.createProduct()
print("Got a new device: " + product2.getProduct())

Пример 2

protocol Currency {
    func symbol() -> String
    func code() -> String
}

class Euro : Currency {
    func symbol() -> String {
        return "€"
    }

    func code() -> String {
        return "EUR"
    }
}

class UnitedStatesDolar : Currency {
    func symbol() -> String {
        return "$"
    }

    func code() -> String {
        return "USD"
    }
}

enum Country {
    case unitedStates, spain, uk, greece
}

enum CurrencyFactory {
    static func currency(for country:Country) -> Currency? {

        switch country {
            case .spain, .greece :
                return Euro()
            case .unitedStates :
                return UnitedStatesDolar()
            default:
                return nil
        }

    }
}

Применение

let noCurrencyCode = "No Currency Code Available"

CurrencyFactory.currency(for: .greece)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .spain)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .unitedStates)?.code() ?? noCurrencyCode
CurrencyFactory.currency(for: .uk)?.code() ?? noCurrencyCode
Поделиться
Популярное