C# design pattern --- bridge mode

Bridge Pattern

The bridge pattern (Bridge Pattern) is to separate the abstract part from its implementation part, so that they can be changed independently, making the design more scalable, and its implementation details are transparent to customers. It is an object structure mode, also known as handle body (Handle and Body) mode or interface (interface) mode. In a software system, some types have two or more dimensional changes due to their own logic, so Bridge Pattern needs to be used. Because the aggregation relationship is established on the abstract layer, developers are required to design and program for abstraction, which increases the difficulty of system understanding and design.

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();
            }
        }
    }
}

 

Guess you like

Origin blog.csdn.net/lwf3115841/article/details/131799498