Skip to content

Instantly share code, notes, and snippets.

@torpedo87
Created December 31, 2018 06:52
Facade pattern

Facade pattern

  • 복잡한 시스템에서 추상화된 인터페이스인 facade 를 만들어서 제공해서 서로 자세하게 알지 못하게 한다
  • The facadeprovides simple methods to interact with the system. Behind the scenes, it owns and interacts with its dependencies, each of which performs a small part of a complex task.

facade

public class OrderFacade {
  public let inventoryDatabase: InventoryDatabase
  public let shippingDatabase: ShippingDatabase
  
  public init(inventoryDatabase: InventoryDatabase,
              shippingDatabase: ShippingDatabase) {
    self.inventoryDatabase = inventoryDatabase
    self.shippingDatabase = shippingDatabase
  }
  
  
  public func placeOrder(for product: Product,
                         by customer: Customer) {
    let count = inventoryDatabase.inventory[product, default: 0]
    
    guard count > 0 else {
      return
    }
    
    inventoryDatabase.inventory[product] = count - 1
    
    var shipments = shippingDatabase.pendingShipments[customer, default: []]
    shipments.append(product)
    shippingDatabase.pendingShipments[customer] = shipments
  }
}

dependencies

  • facade 가 포함하는 것들
public struct Customer {
  
  public let identifier: String
  public var address: String
  public var name: String
}

extension Customer: Hashable {
  
  public var hashValue: Int {
    return identifier.hashValue
  }
  
  public static func ==(lhs: Customer, rhs: Customer) -> Bool {
    return lhs.identifier == rhs.identifier
  }
}

public struct Product {
  public let identifier: String
  public var name: String
  public var cost: Double
}

extension Product: Hashable {
  
  public var hashValue: Int {
    return identifier.hashValue
  }
  
  public static func ==(lhs: Product, rhs: Product) -> Bool {
    return lhs.identifier == rhs.identifier
  }
}




public class InventoryDatabase {
  
  public var inventory: [Product: Int] = [:]
  
  public init(inventory: [Product:Int]) {
    self.inventory = inventory
  }
  
}


public class ShippingDatabase {
  public var pendingShipments: [Customer: [Product]] = [:]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment