抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
下面是参照菜鸟教程里的Java实例写的swift版本,问底会贴出原文链接。
1、为形状创建一个接口。
protocol Shape {
func draw()
}
2、创建实现接口的实体类。
class Rectangle: Shape {
func draw() {
print("Inside Rectangle::draw() method.")
}
}
class Square: Shape {
func draw() {
print("Inside Square::draaw() method.")
}
}
class Circle: Shape {
func draw() {
print("Inside Circle::draw() method.")
}
}
3、为颜色创建一个接口。
protocol Color {
func fill()
}
4、创建实现接口的实体类。
class Red: Color {
func fill() {
print("Inside Red::fill() method.")
}
}
class Green: