个人网站可以做推广不软件开发公司经营范围
桥接模式(Bridge Pattern)是一种结构型设计模式,旨在将抽象与实现分离,使得两者可以独立变化。通过使用桥接模式,可以避免在多个维度上进行继承,降低代码的复杂度,从而提高系统的可扩展性。
组成部分
- 抽象类(Abstraction): 定义高层的抽象接口,并持有对实现的引用。
- 扩展抽象类(RefinedAbstraction): 继承自抽象类,提供具体的扩展实现。
- 实现接口(Implementor): 定义实现部分的接口。
- 具体实现类(ConcreteImplementor): 实现实现接口的具体类。
JAVA:
// 1、定义一个图像接口
public interface Graph {//画图方法 参数:半径 长 宽public void drawGraph(int radius, int x, int y);
}
// 红色图形
public class RedGraph implements Graph{@Overridepublic void drawGraph(int radius, int x, int y) {System.out.println("红色");}
}
// 创建一个形状
public abstract class Shape {public Graph graph;public Shape(Graph graph){this.graph = graph;}public abstract void draw();
}
// 圆形
public class Circle extends Shape{private int radius;private int x;private int y;public Circle(int radius, int x, int y, Graph graph) {super(graph);this.radius = radius;this.x = x;this.y = y;}@Overridepublic void draw() {System.out.println("圆形");graph.drawGraph(radius, x, y);}
}
@Test(description = "桥接模式")public void bridgePatternTest(){//创建圆形Shape shape = new Circle(10, 100, 100, new RedGraph());shape.draw();}
GO:
package bridgeimport "fmt"// 桥接模式// IMsgSender 消息发送接口
type IMsgSender interface {// Send 发送动作函数Send(msg string) error
}// EmailMsgSender发送邮件
// 可能还有 电话、短信等各种实现
type IMsgReceiver struct {emails []string
}func (I IMsgReceiver) Send(msg string) error {// 这里去发送消息fmt.Println(msg, "消息发送成功")return nil
}func NewEmailMsgSender(emails []string) *IMsgReceiver {return &IMsgReceiver{emails: emails}
}// INotification 通知接口
type INotification interface {// Notify 通报函数Notify(msg string) error
}// ErrorNotification 错误通知
// 后面可能还有 warning 各种级别
type ErrorNotification struct {sender IMsgSender
}// Notify 发送通知
func (e ErrorNotification) Notify(msg string) error {return e.sender.Send(msg)
}func NewErrorNotification(sender IMsgSender) *ErrorNotification {return &ErrorNotification{sender: sender}
}
func TestBridge(t *testing.T) {sender := NewEmailMsgSender([]string{"test@test.com"})n := NewErrorNotification(sender)err := n.Notify("test msg")assert.Nil(t, err)
}