最近换了一份新工作,全新的开始,一切还在奋斗的道路上,自己给自己打个气!
设计模式系列很久没有更新了,废话不多说,开始今天的桥接模式。
定义:
何为Bridge模式?我们知道,实现与抽象之间总是存在着强依赖,Bridge模式的意义就是解耦实现与抽象,这意味着实现与抽象不再有着静态的依赖关系,它们彼此可以拥有独立的变化,从而互不影响。
UML:

实例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BridgePattern
{
/// <summary>
/// This is abstraction, represents shape.
/// </summary>
public interface IShape
{
/// <summary>
/// The shape has a property called Drawing, which represents implemention of drawing behavior.
/// </summary>
IDrawing Drawing { get; set; }
/// <summary>
/// The shape has a method called Draw. If you don't adopt Bridge pattern, in general, you should implement this method to draw.
/// </summary>
/// <returns></returns>
string Draw();
}
/// <summary>
/// This is a concrete abstraction. represents circle shape.
/// </summary>
public class CircleShape : IShape
{
public CircleShape(IDrawing drawing)
{
Drawing = drawing;
}
public IDrawing Drawing { get; set; }
/// <summary>
/// The method Draw uses IDrawing to bridge. You will find that you don't need to implement concrete darwing behavior, you just forward the request to IDrawing.
/// </summary>
/// <returns></returns>
public string Draw()
{
return Drawing.Draw();
}
}
/// <summary>
/// This is abstraction of implementation, represents abstract implementation, it has ability to independent with IShape.
/// </summary>
public interface IDrawing
{
string Draw();
}
/// <summary>
/// This is concrete implementation, derived from IDrawing.
/// </summary>
public class CircleDrawing : IDrawing
{
public string Draw()
{
return "Draws a circle.";
}
}
class Program
{
static void Main(string[] args)
{
IDrawing drawing = new CircleDrawing(); //Get a circle drawing which will be used later.
IShape shape = new CircleShape(drawing);// Get a circle shape which uses drawing object to draw.
Console.WriteLine(shape.Draw());//Ok, shape draws.
Console.ReadKey();
}
}
}
输出:


One Reply to “桥接模式 (Bridge Pattern)-结构型模式第五篇”