桥接模式是一种结构型设计模式, 可将一个大类或一系列紧密相关的类拆分为抽象和实现两个独立的层次结构, 从而能在开发时分别使用。
我们定义一个抽象的图形接口和一个图形管理接口:
protocol Shape {
var shapManager: ShapeManager { get set }
func draw() -> UIImage
}
protocol ShapeManager {
var linecolor: UIColor { get }
var lineWidth: CGFloat { get }
var filecolor: UIColor { get }
}
这个类又一个属性shapManager,用来管理图形的一些属性,有一个draw方法,负责绘制图形。
接下来我们分别实现正方形和圆形:
class SquerShape: Shape {
init(shapManager: ShapeManager) {
self.shapManager = shapManager
}
var shapManager: ShapeManager
func draw() -> UIImage {
UIGraphicsBeginImageContext(CGSize.init(width: 100, height: 100))
let p = UIBezierPath.init(rect: CGRect.init(x: 25, y: 25, width: 50, height: 50))
p.lineWidth = self.shapManager.lineWidth
self.shapManager.linecolor.setStroke()
self.shapManager.filecolor.setFill()
p.fill()
p.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
class CircleShape: Shape {
init(shapManager: ShapeManager) {
self.shapManager = shapManager
}
var shapManager: ShapeManager
func draw() -> UIImage {
UIGraphicsBeginImageContext(CGSize.init(width: 100, height: 100))
let p = UIBezierPath.init()
p.addArc(withCenter: CGPoint(x: 50, y: 50), radius: 25, startAngle: 0, endAngle: 360, clockwise: true)
p.lineWidth = self.shapManager.lineWidth
self.shapManager.linecolor.setStroke()
self.shapManager.filecolor.setFill()
p.fill()
p.stroke()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
具体的图形类在draw方法里根据shapManager的属性,绘制相应的图形并返回。
接下来我们我们实现两种管理类,分别设置一下属性:
class ShapeManager1: ShapeManager {
var linecolor: UIColor
var lineWidth: CGFloat
var filecolor: UIColor
init() {
self.lineWidth = 1
self.linecolor = .red
self.filecolor = .white
}
}
class ShapeManager2: ShapeManager {
var linecolor: UIColor
var lineWidth: CGFloat
var filecolor: UIColor
init() {
self.lineWidth = 3
self.linecolor = .black
self.filecolor = .blue
}
}
最后在客户端调用:
let imageView1 = UIImageView.init(image: SquerShape.init(shapManager: ShapeManager1.init()).draw())
let imageView2 = UIImageView.init(image: SquerShape.init(shapManager: ShapeManager2.init()).draw())
let imageView3 = UIImageView.init(image: CircleShape.init(shapManager: ShapeManager1.init()).draw())
let imageView4 = UIImageView.init(image: CircleShape.init(shapManager: ShapeManager2.init()).draw())
let stack = UIStackView.init(arrangedSubviews: [imageView1, imageView2, imageView3, imageView4])
stack.frame = self.view.bounds
stack.alignment = .center
stack.distribution = .equalSpacing
stack.axis = .vertical
self.view.addSubview(stack)
长成这样:
这里只有四种图形,看不出来桥接模式的好处,假如要增加一种颜色的图形,我们只用增加一个ShapeManager类就可以实现,到时就会有六种图形,假如我们有十个图形,配上十种颜色,我们就可以得到100种具体图形。我们用20个类就实现了100种图形,假如用类继承的方式,我们需要100个类。这就是桥接模式的魅力!
网友评论