Created
October 11, 2020 14:26
-
-
Save perpeer/9cc2ada41666656f06dbd9384011e2e0 to your computer and use it in GitHub Desktop.
Swift Factory Method Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| enum ButtonStyle: String, RawRepresentable { | |
| case dark, light, `default` | |
| } | |
| protocol ButtonStyleProductProtocol { | |
| var style: ButtonStyle { get set } | |
| var font: UIFont { get set } | |
| var description: String { get } | |
| } | |
| extension ButtonStyleProductProtocol { | |
| var description: String { | |
| return "Button style: \(style.rawValue), \(font.pointSize)" | |
| } | |
| } | |
| class ButtonStyleProduct: ButtonStyleProductProtocol { | |
| var style: ButtonStyle | |
| var font: UIFont | |
| fileprivate init(style: ButtonStyle, font: UIFont) { | |
| self.style = style | |
| self.font = font | |
| } | |
| } | |
| class DefaultButtonStyleProduct: ButtonStyleProductProtocol { | |
| var style: ButtonStyle | |
| var font: UIFont | |
| fileprivate init() { | |
| self.style = .default | |
| self.font = .systemFont(ofSize: 12) | |
| } | |
| } | |
| protocol ButtonStyleCreatorProtocol { | |
| func createButton(with style: ButtonStyle) -> ButtonStyleProductProtocol | |
| } | |
| class ButtonStyleCreator: ButtonStyleCreatorProtocol { | |
| func createButton(with style: ButtonStyle) -> ButtonStyleProductProtocol { | |
| switch style { | |
| case .dark: | |
| let style = ButtonStyle.dark | |
| let font = UIFont.systemFont(ofSize: 60) | |
| return ButtonStyleProduct(style: style, font: font) | |
| case .light: | |
| let style = ButtonStyle.light | |
| let font = UIFont.systemFont(ofSize: 12) | |
| return ButtonStyleProduct(style: style, font: font) | |
| default: | |
| return DefaultButtonStyleProduct() | |
| } | |
| } | |
| } | |
| let darkButtonCreator = ButtonStyleCreator().createButton(with: .dark) | |
| let lightButtonCreator = ButtonStyleCreator().createButton(with: .light) | |
| let defaultButtonCreator = ButtonStyleCreator().createButton(with: .default) | |
| print(darkButtonCreator.description) | |
| print(lightButtonCreator.description) | |
| print(defaultButtonCreator.description) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment