Giter Site home page Giter Site logo

factory-method's Introduction

Swift 4.2 XCode 10+ iOS iOS 12 Licence MIT

Factory Method

Фабричный метод (Виртуальный конструктор)

Это порождающий паттерн проектирования, который определяет общий интерфейс для создания объектов в суперклассе, позволяя подсклассам изменять тип создаваемых объектов.

Positive side

  • Избавляет класс от привязки к конкретным классам продуктов (завязываемся на тип протокола)
  • Выделяет код производства продуктов в одно место, упрощая поддержку кода (знаем, если мы хотим что-то изменить, то идем в конкретное место, а не по всему проекту бегаем)
  • упрощает добавление новых продуктов в программу
  • Реализует принцип открытости / закрытости (2 принцип солида) (основные принципы ООП)

Negative side

  • Может привести к созданию больших параллельных иерархий классов, так как для каждого класса продукта надо создать свой подкласс создателя

Create protocol

protocol Vehicle {
    var type: String { get }

    func startPoint()

    func endPoint()
}

Create kitchen

enum Transport {
    case bus, plane, supercar, train
}

class Singletone {
    static let shared = Singletone()

    func createDrive(type: Transport) -> Vehicle {
        switch type {
        case .bus:
            return Bus()
        case .plane:
            return Plane()
        case .supercar:
            return SuperCar()
        case .train:
            return Train()
        }
    }
}

Create product

class Bus: Vehicle {
    var type: String = "Bus"

    func startPoint() {
        print("Started transportation by bus")
    }

    func endPoint() {
        print("Bus transportation ended")
    }
}

Workspace

Create func for choose transport

func chooseTransport(name: Transport) {
    let option = Singletone.shared.createDrive(type: name)
    arrayDrives.append(option)
}

Create func for output data

func printResult() {
    for i in arrayDrives {
        i.startPoint()
        i.endPoint()
    }
}

ViewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    chooseTransport(name: .bus)
    printResult()
}

Another example

Requirements

  • Swift 4.2
  • iOS 12 or higher

Authors

  • Alexandr Kustov - ELEV0

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

License

This project is licensed under the MIT License.

factory-method's People

Contributors

elev0 avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.