今天的桥接器模式,和昨天的转接器模式一样,都是非常常见的模式,可能我们不自觉当中都会使用到。话不多说,我们就先来看例子吧!
这里有一个 Shape
类别,定义了基本的属性 name
和 color
。接着我们可以建立 Square
类别,他继承了 Shape
,在执行细节上,直接将 name
设定为 "square"。
当然我们也可以建立一个 RedSquare
类别,同样是继承 Shape
,在执行细节上,直接将 name
设定为 "square"、将 color
设定为 "red"
class Shape {
name: string
color: string
}
class Square extends Shape {
constructor() {
super()
this.name = 'square'
}
}
class RedSquare extends Shape {
constructor() {
super()
this.name = 'triangle'
this.color = 'red'
}
}
到目前为止看起来都很合理
如果现在我们希望增加一个 Triangle
类别,以及为各种 Shape
新增一个颜色,譬如蓝色,那麽我们就需要建立
四种类别。如果我们有十种形状、十种颜色,那麽如果要建立出所有颜色的形状,那麽就需要建立 100 个新类别,看起来就有点不合理了。这时候该怎麽办呢?
不如,我们就把形状和颜色先拆开来处理,然後找一个方法,将两者连接再一起。
让我们先来处理颜色的部分。这里我先建立一个抽象类别 Color
,定义未来各种颜色类别的基本样貌。接着,我们建立了 Green
和 Blue
类别,用来产生颜色的实例
class Color {
color: string
}
class Green extends Color {
color = 'green'
constructor(){
super()
}
}
class Blue extends Color {
color = 'blue'
constructor(){
super()
}
}
之後,让我们回头看看 Shape
这边。我们同样有 Shape
这个抽象类别,紧接着建立 Square
和 Triangle
两个类别。
不过这里我们要怎麽把形状跟颜色连接在一起呢?这里我们在 constructor 当中放入颜色,让不同形状的实例能够具备该有的颜色
class Shape {
name: string
color: string
}
class Square extends Shape {
constructor(color: string) {
super()
this.name = 'square'
this.color = color
}
getDescription(): string {
return `I am the best ${this.color} ${this.name}!`
}
}
class Triangle extends Shape {
constructor(color: string) {
super()
this.name = 'triangle'
this.color = color
}
getDescription(): string {
return `I am a ${this.color} ${this.name}!`
}
}
最後,我们先建立颜色的实例,接着,就可以创造出各种颜色的形状了!
const green = new Green()
const blue = new Blue()
const greenSquare = new Square(green.color)
const blueSquare = new Square(blue.color)
const greenTriangle = new Triangle(green.color)
const blueTriangle = new Triangle(blue.color)
greenSquare.getDescription() // 'I am the best green square!'
blueSquare.getDescription() // 'I am the best blue square!'
greenTriangle.getDescription() // 'I am a green triangle!'
blueTriangle.getDescription() // 'I am a blue triangle!'
桥接器模式将一个物件当中的不同属性拆开来处理(譬如这里的 shape 和 color),让程序码具备扩充性。但是如果这些属性彼此之间高度相关的话,那麽就比较难轻易的实作桥接,或是会让程序码本身变得更为复杂。
<<: Day26 vue.js功能展示ep2之有"大麻"烦(cros跨域)
遍历字典 Items() 可以取得key跟value Key() 只取得key Values() ...
上一篇我们设计了 I2C Master 的状态机,那麽我们今天要来引用上次完成的状态机模块来实现 I...
前言 我之前有写透过 lock or CAS 来防治,Racing condition 问题,但如果...
如果类别本身已经济成某个妇类别,但现在又要继承Thread类别来建立执行绪,马上就会面临到一个问题-...
今天要来用 Template Driven Forms 的方式实作一个很简易的动态表单,使用上有点...