Leetcode - Island Perimeter
Leetcode - 3Sum With Multiplicity

设计模式 - 桥接模式

violet posted @ Jul 08, 2020 02:13:07 AM in 算法 with tags Design Pattern Golang , 191 阅读

意图:将抽象部分与实现部分分离,使它们都可以独立的变化。

主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。

何时使用:实现系统可能有多个角度分类,每一种角度都可能变化。

如何解决:把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。

关键代码:抽象类依赖实现类。

优点: 1、抽象和实现的分离。 2、优秀的扩展能力。 3、实现细节对客户透明。

缺点:桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。

使用场景: 1、如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系。 2、对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用。 3、一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

注意事项:对于两个独立变化的维度,使用桥接模式再适合不过了。

package main

import "fmt"

type DrawAPI interface {
	DrawCircle(int, int, int)
}

type RedCircle struct{}
type GreenCircle struct{}

func (*RedCircle) DrawCircle(radius, x, y int) {
	fmt.Println("draw red circle, radius, x, y: ", radius, x, y)
}

func (*GreenCircle) DrawCircle(radius, x, y int) {
	fmt.Println("draw green circle, radius, x, y: ", radius, x, y)
}

type Shape struct {
	drawAPI DrawAPI
}

func (s *Shape) Draw(x, y, radius int) {
	s.drawAPI.DrawCircle(x, y, radius)
}

type Circle struct {
	x, y, radius int
	shape        *Shape
}

func NewCircle(x, y, radius int) *Circle {
	return &Circle{
		x:      x,
		y:      y,
		radius: radius,
	}
}

func (c *Circle) Draw() {
	c.shape.Draw(c.x, c.y, c.radius)
}

func main() {
	circle := NewCircle(1, 2, 3)
	circle.shape = &Shape{drawAPI: &RedCircle{}}
	circle.Draw()

	circle.shape = &Shape{drawAPI: &GreenCircle{}}
	circle.Draw()
}
192.168.l.l asus rou 说:
Feb 07, 2023 01:09:05 PM

To assist you in ensuring that your Asus router is appropriately configured, we have produced this tutorial, and via this post, we will lead you through the many configuration procedures needed in finishing the setup as fast as possible. 192.168.l.l asus router login After you have logged in, click on the Go button. Following that, you will be sent to the administrator password credentials setting page. On this screen, enter your login name, password, and reenter your password, then click the next button.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter