工厂方法
用于创建单一产品对象,通过子类决定具体实例化的产品类。适用于需要在运行时根据不同条件创建不同类的对象的场景。
适用场景
- 需要创建的对象类型在运行时才确定。
- 需要将对象的创建过程封装在子类中。
- 系统中的对象有多个变种,需要通过子类来决定创建哪一个变种。
protocol DatabaseConnection {
func connect()
func disconnect()
}
class MySQLConnection: DatabaseConnection {
func connect() {
print("Connecting to MySQL database.")
}
func disconnect() {
print("Disconnecting from MySQL database.")
}
}
class PostgreSQLConnection: DatabaseConnection {
func connect() {
print("Connecting to PostgreSQL database.")
}
func disconnect() {
print("Disconnecting from PostgreSQL database.")
}
}
class SQLiteConnection: DatabaseConnection {
func connect() {
print("Connecting to SQLite database.")
}
func disconnect() {
print("Disconnecting from SQLite database.")
}
}
protocol DatabaseFactory {
func createConnection() -> DatabaseConnection
}
class MySQLFactory: DatabaseFactory {
func createConnection() -> DatabaseConnection {
return MySQLConnection()
}
}
class PostgreSQLFactory: DatabaseFactory {
func createConnection() -> DatabaseConnection {
return PostgreSQLConnection()
}
}
class SQLiteFactory: DatabaseFactory {
func createConnection() -> DatabaseConnection {
return SQLiteConnection()
}
}
func performDatabaseOperations(factory: DatabaseFactory) {
let connection = factory.createConnection()
connection.connect()
// 执行数据库操作
connection.disconnect()
}
// 使用MySQL工厂
let mySQLFactory = MySQLFactory()
performDatabaseOperations(factory: mySQLFactory)
// 使用PostgreSQL工厂
let postgreSQLFactory = PostgreSQLFactory()
performDatabaseOperations(factory: postgreSQLFactory)
// 使用SQLite工厂
let sqliteFactory = SQLiteFactory()
performDatabaseOperations(factory: sqliteFactory)
抽象工厂
用于创建一系列相关或相互依赖的产品对象,通过具体工厂类实现产品族的一致性。适用于需要创建一组相关联的对象,并且需要保证它们之间的兼容性的场景。
适用场景
- 需要创建一系列相关或相互依赖的对象。
- 系统中的产品对象有多个产品族,每个产品族中的对象具有一致性。
- 需要确保在一个产品族中的对象一起使用时是兼容的。
protocol Button {
func render()
}
protocol TextField {
func render()
}
class WindowsButton: Button {
func render() {
print("Rendering Windows button.")
}
}
class MacOSButton: Button {
func render() {
print("Rendering MacOS button.")
}
}
class WindowsTextField: TextField {
func render() {
print("Rendering Windows text field.")
}
}
class MacOSTextField: TextField {
func render() {
print("Rendering MacOS text field.")
}
}
protocol GUIFactory {
func createButton() -> Button
func createTextField() -> TextField
}
class WindowsFactory: GUIFactory {
func createButton() -> Button {
return WindowsButton()
}
func createTextField() -> TextField {
return WindowsTextField()
}
}
class MacOSFactory: GUIFactory {
func createButton() -> Button {
return MacOSButton()
}
func createTextField() -> TextField {
return MacOSTextField()
}
}
func createUI(factory: GUIFactory) {
let button = factory.createButton()
let textField = factory.createTextField()
button.render()
textField.render()
}
let windowsFactory = WindowsFactory()
createUI(factory: windowsFactory)
let macFactory = MacOSFactory()
createUI(factory: macFactory)