当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 设计模式系列 - 桥接模式

设计模式系列 - 桥接模式

2018年12月18日  | 移动技术网IT编程  | 我要评论

使用桥接模式可以将类型的抽象和具体实现进行分离,两者通过桥接模式进行关联,从而达到解耦

介绍

桥接模式属于结构型模式。在现实世界中,我们装修房子时,布线的工人和安装空调的工人之间可以同时工作,不用互相依赖。而对于屋主人来讲也不用关系他们具体时怎么工作的,只需要等他们完成即可。在软件开发中,当我们面对一个业务中两个独立的子业务时,使用桥接模式是一个不错的选择。

类图描述

由上图我们可以看到,我们定义了一个抽象类 shape 来继承 idrawapi 接口,然后定义两种绘制方式 greencircleredcircle ,最后上层通过将具体绘制传递给 circle 即可。

代码实现

1、定义绘制接口

    public interface idrawapi
    {
        void drawcircle(int radius, int x, int y);
    }

2、定义具体绘制类

public class redcircle:idrawapi
{
    public void drawcircle(int radius, int x, int y)
    {
        console.writeline($"drawing circle[color:red,radius:{radius},x:{x},y:{y}]");
    }
}

public class greencircle:idrawapi
{
    public void drawcircle(int radius, int x, int y)
    {
        console.writeline($"drawing circle[color:green,radius:{radius},x:{x},y:{y}]");
    }
}

3、定义抽象形状类

public abstract class shape
{
    protected idrawapi drawapi;

    protected shape(idrawapi drawapi) => this.drawapi = drawapi;

    public abstract void draw();
}

4、定义具体形状类

public class circle:shape
{
    private int x, y, radius;
    public circle(int x,int y,int radius,idrawapi drawapi) : base(drawapi)
    {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    public override void draw()
    {
        drawapi.drawcircle(radius, x, y);
    }
}

5、上层调用

class program
{
    static void main(string[] args)
    {
        shape redcircle = new circle(100, 100, 10, new redcircle());
        redcircle.draw();

        shape greencircle = new circle(100, 100, 10, new greencircle());
        greencircle.draw();

        console.readkey();
    }
}

总结

桥接模式将抽象和实现进行了分离,让它们能独立变化,使得具体的实现细节不用暴露给上层。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网