C#设计模式之---桥接模式

桥接模式(Bridge Pattern)

桥接模式(Bridge Pattern)是将抽象部分与它的实现部分分离,使它们都可以独立地变化,使得设计更具扩展性,其实现细节对客户透明。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(interface)模式。在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,就需要使用桥接模式(Bridge Pattern)。由于聚合关系建立在抽象层,要求开发者针对抽象化进行设计与编程,这增加了系统的理解与设计难度。

using System;
namespace ConsoleApplication
{
    interface IDrawingAPI
    {
        void DrawCircle(double x, double y, double radius);
    }
    /** "具体实现" 1/2 */
    class DrawingAPI1 : IDrawingAPI
    {
        public void DrawCircle(double x, double y, double radius)
        {
            Console.WriteLine("API1.circle at {0}:{1} radius {2}", x, y, radius);
        }
    }
    /** "具体实现" 2/2 */
    class DrawingAPI2 : IDrawingAPI
    {
        public void DrawCircle(double x, double y, double radius)
        {
            Console.WriteLine("API2.circle at {0}:{1} radius {2}", x, y, radius);
        }
    }
    /** "抽象" */
    interface IShape
    {
        void Draw();
        void ResizeByPercentage(double pct);
    }
    // /** "Refined Abstraction:扩展抽象在下面一层接受更详细的细节。对实现者隐藏更精细的元素。" */
    class CircleShape : IShape
    {
        private double x, y, radius;
        private IDrawingAPI drawingAPI;
        public CircleShape(double x, double y, double radius, IDrawingAPI drawingAPI)
        {
            this.x = x; this.y = y;
            this.radius = radius;
            this.drawingAPI = drawingAPI;
        }
        public void Draw()
        {
            drawingAPI.DrawCircle(x, y, radius);
        }
        public void ResizeByPercentage(double pct)
        {
            radius *= pct;
        }
    }
    /** "Client" */
    class Program
    {
        public static void Main(string[] args)
        {
            IShape[] shapes = new IShape[2];
            shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());
            shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());
            foreach (IShape shape in shapes)
            {
                shape.ResizeByPercentage(2.5); shape.Draw();
            }
        }
    }
}

 

你可能感兴趣的:(C#遗忘系列,设计模式,桥接模式)